Ticket #24928: oauth-rationalise-24928.patch

File oauth-rationalise-24928.patch, 231.1 KB (added by wangi, 4 hours ago)
  • src/org/openstreetmap/josm/data/Preferences.java

    diff --git src/org/openstreetmap/josm/data/Preferences.java src/org/openstreetmap/josm/data/Preferences.java
    index 48cb104644..c9553a5da8 100644
    public class Preferences extends AbstractPreferences {  
    8585
    8686    /** remove if key equals */
    8787    private static final String[] OBSOLETE_PREF_KEYS = {
    88         // nothing ATM
     88        "oauth.access-token.key", // OAuth 1.0a token, unused since OAuth 1.0a was removed (#22810). To remove end of 2027
     89        "oauth.access-token.secret", // OAuth 1.0a token, unused since OAuth 1.0a was removed (#22810). To remove end of 2027
    8990    };
    9091
    9192    /** remove if key starts with */
  • src/org/openstreetmap/josm/data/UserIdentityManager.java

    diff --git src/org/openstreetmap/josm/data/UserIdentityManager.java src/org/openstreetmap/josm/data/UserIdentityManager.java
    index 36b20a9ec0..62b024d401 100644
    public final class UserIdentityManager implements PreferenceChangedListener {  
    8585
    8686    private String userName;
    8787    private UserInfo userInfo;
    88     private boolean accessTokenKeyChanged;
    89     private boolean accessTokenSecretChanged;
    9088
    9189    private UserIdentityManager() {
    9290    }
    … … public final class UserIdentityManager implements PreferenceChangedListener {  
    296294                setPartiallyIdentified(getUserName());
    297295            }
    298296            break;
    299         case "oauth.access-token.key":
    300             accessTokenKeyChanged = true;
    301             break;
    302         case "oauth.access-token.secret":
    303             accessTokenSecretChanged = true;
    304             break;
    305         default: // Do nothing
    306             if (evt.getKey() != null && evt.getKey().equals("oauth.access-token.parameters.OAuth20." + OsmApi.getOsmApi().getHost())) {
    307                 accessTokenKeyChanged = true;
    308                 accessTokenSecretChanged = true;
    309             }
    310         }
    311         // oauth.access-token.parameters.OAuth20.api.openstreetmap.org
    312 
    313         if (accessTokenKeyChanged && accessTokenSecretChanged) {
    314             accessTokenKeyChanged = false;
    315             accessTokenSecretChanged = false;
    316             if (OsmApi.isUsingOAuthAndOAuthSetUp(OsmApi.getOsmApi())) {
    317                 getInstance().initFromOAuth();
    318             } else if (OsmApi.isUsingOAuth()) {
    319                 setAnonymous();
     297        default:
     298            // the OAuth 2 token of the current server was stored or removed, e.g. oauth.access-token.object.OAuth20.api.openstreetmap.org;
     299            // its parameters are kept when it is removed, so they do not tell
     300            if (("oauth.access-token.object.OAuth20." + OsmApi.getOsmApi().getHost()).equals(evt.getKey())) {
     301                if (OsmApi.isUsingOAuthAndOAuthSetUp(OsmApi.getOsmApi())) {
     302                    getInstance().initFromOAuth();
     303                } else if (OsmApi.isUsingOAuth()) {
     304                    setAnonymous();
     305                }
    320306            }
    321307        }
    322308    }
  • src/org/openstreetmap/josm/data/oauth/OAuth20Parameters.java

    diff --git src/org/openstreetmap/josm/data/oauth/OAuth20Parameters.java src/org/openstreetmap/josm/data/oauth/OAuth20Parameters.java
    index 0214627dad..a665acbb02 100644
    import jakarta.json.JsonStructure;  
    1515import jakarta.json.JsonValue;
    1616
    1717import org.openstreetmap.josm.spi.preferences.Config;
     18import org.openstreetmap.josm.tools.Logging;
     19import org.openstreetmap.josm.tools.Utils;
    1820
    1921/**
    2022 * Parameters for OAuth 2.0
    … … public final class OAuth20Parameters implements IOAuthParameters {  
    130132        return this.apiUrl;
    131133    }
    132134
     135    /**
     136     * {@inheritDoc}
     137     * <p>
     138     * The parameters are stored under the host of the API, where the access token of the server stores its
     139     * parameters as well.
     140     */
    133141    @Override
    134142    public void rememberPreferences() {
    135         Config.getPref().put("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + this.apiUrl,
    136                 this.toPreferencesString());
     143        if (Utils.isEmpty(this.apiUrl)) {
     144            // there is no server to store them for
     145            Logging.warn("OAuth parameters of client id {0} have no API URL and are not stored", this.clientId);
     146            return;
     147        }
     148        final String key = OAuthParameters.getPreferenceKey(this.apiUrl);
     149        Config.getPref().put(key, this.toPreferencesString());
     150        // earlier versions of JOSM stored them under the API URL
     151        final String apiUrlKey = "oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + this.apiUrl;
     152        if (!key.equals(apiUrlKey)) {
     153            Config.getPref().put(apiUrlKey, null);
     154        }
    137155    }
    138156
    139157    @Override
  • src/org/openstreetmap/josm/data/oauth/OAuth20Token.java

    diff --git src/org/openstreetmap/josm/data/oauth/OAuth20Token.java src/org/openstreetmap/josm/data/oauth/OAuth20Token.java
    index c27d35eab9..06ff53079b 100644
    public final class OAuth20Token implements IOAuthToken {  
    5151        this(oauthParameters, new InputStreamReader(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
    5252    }
    5353
     54    /**
     55     * Create a bearer token from the access token alone, such as a token issued outside JOSM and pasted by the user.
     56     * It has no refresh token, and works with nothing else: the parameters only need the API URL the token is for.
     57     * @param oauthParameters The parameters for the OAuth token
     58     * @param accessToken The access token
     59     * @return The bearer token
     60     * @since xxx
     61     */
     62    public static OAuth20Token fromAccessToken(IOAuthParameters oauthParameters, String accessToken) {
     63        final String json = Json.createObjectBuilder()
     64                .add(ACCESS_TOKEN, accessToken)
     65                .add(TOKEN_TYPE, "bearer")
     66                .build().toString();
     67        try {
     68            return new OAuth20Token(oauthParameters, json);
     69        } catch (OAuth20Exception e) {
     70            // both required fields are present
     71            throw new JosmRuntimeException(e);
     72        }
     73    }
     74
    5475    OAuth20Token(IOAuthParameters oauthParameters, Reader bufferedReader) throws OAuth20Exception {
    5576        this.oauthParameters = oauthParameters;
    5677        try (JsonReader reader = Json.createReader(bufferedReader)) {
  • src/org/openstreetmap/josm/data/oauth/OAuthParameters.java

    diff --git src/org/openstreetmap/josm/data/oauth/OAuthParameters.java src/org/openstreetmap/josm/data/oauth/OAuthParameters.java
    index c3e23f4d25..85a497f04e 100644
    public final class OAuthParameters {  
    3636    private static final String OSM_API_DEFAULT = "https://api.openstreetmap.org/api";
    3737    private static final String OSM_API_DEV = "https://api06.dev.openstreetmap.org/api";
    3838    private static final String OSM_API_MASTER = "https://master.apis.dev.openstreetmap.org/api";
     39    /** Whether the default parameters are used; one setting for each host, with the setting for all hosts as fallback */
     40    private static final String USE_DEFAULT = "oauth.settings.use-default";
    3941
    4042    private OAuthParameters() {
    4143        // Hide constructor
    … … public final class OAuthParameters {  
    8082
    8183    /**
    8284     * Get the OAuth 2.0 parameters the user entered in the advanced OAuth settings and saved with
    83      * {@link IOAuthParameters#rememberPreferences()}. Until a token exists, this is the only place a
    84      * client id for a server not in {@link #createDefault(String, OAuthVersion)} can come from.
    85      * {@link OAuth20Parameters#rememberPreferences()} keys by the API URL as given; callers may pass
    86      * either the URL or its host, so both are tried.
     85     * {@link IOAuthParameters#rememberPreferences()}, or the parameters of the access token of the server. Until a
     86     * token exists, this is the only place a client id for a server not in
     87     * {@link #createDefault(String, OAuthVersion)} can come from.
     88     * {@link OAuth20Parameters#rememberPreferences()} keys by the host of the API, as the access token is; earlier
     89     * versions of JOSM keyed them by the API URL, so callers pass that too.
    8790     * @param keys The preference key suffixes to try, in order
    8891     * @return The remembered parameters, or {@code null} if none are saved or they cannot be parsed
    8992     * @since 19627
    … … public final class OAuthParameters {  
    110113        return null;
    111114    }
    112115
     116    /**
     117     * Get the preference key under which the OAuth 2.0 parameters for the server of an API are stored. This is the
     118     * key of the access token of that server too, see {@link org.openstreetmap.josm.io.auth.CredentialsAgent}.
     119     * @param apiUrl The API URL, or the host of the API
     120     * @return The preference key
     121     * @since xxx
     122     */
     123    static String getPreferenceKey(String apiUrl) {
     124        return "oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + getHost(apiUrl);
     125    }
     126
     127    /**
     128     * Get the host of an API, which is what the OAuth settings and the access token of a server are stored under.
     129     * @param apiUrl The API URL, or the host of the API
     130     * @return The host, or {@code apiUrl} itself if it is not a URL (including {@code null})
     131     * @since xxx
     132     */
     133    public static String getHost(String apiUrl) {
     134        if (Utils.isEmpty(apiUrl)) {
     135            return apiUrl;
     136        }
     137        try {
     138            final String host = new URI(apiUrl).getHost();
     139            return host == null ? apiUrl : host;
     140        } catch (URISyntaxException e) {
     141            Logging.trace(e);
     142            return apiUrl;
     143        }
     144    }
     145
     146    /**
     147     * Determines whether the default OAuth 2.0 parameters are used for the server of an API, that is the ones built
     148     * into JOSM or published by the server, rather than the ones the user entered in the advanced OAuth settings.
     149     * <p>
     150     * This is a setting of each server. Until it is set for a server, the setting earlier versions of JOSM had
     151     * for all servers is used.
     152     * @param apiUrl The API URL, or the host of the API
     153     * @return {@code true} if the default parameters are used
     154     * @since xxx
     155     */
     156    public static boolean isUseDefault(String apiUrl) {
     157        final boolean useDefaultForAll = Config.getPref().getBoolean(USE_DEFAULT, true);
     158        if (Utils.isEmpty(apiUrl)) {
     159            return useDefaultForAll;
     160        }
     161        return Config.getPref().getBoolean(USE_DEFAULT + "." + getHost(apiUrl), useDefaultForAll);
     162    }
     163
     164    /**
     165     * Sets whether the default OAuth 2.0 parameters are used for the server of an API.
     166     * @param apiUrl The API URL, or the host of the API
     167     * @param useDefault {@code true} to use the default parameters, {@code false} to use the ones the user entered
     168     * @see #isUseDefault(String)
     169     * @since xxx
     170     */
     171    public static void setUseDefault(String apiUrl, boolean useDefault) {
     172        if (!Utils.isEmpty(apiUrl)) {
     173            Config.getPref().putBoolean(USE_DEFAULT + "." + getHost(apiUrl), useDefault);
     174        }
     175    }
     176
    113177    private static JsonObject getRFC8414Parameters(String apiUrl) {
    114178        HttpClient client = null;
    115179        try {
    116180            final URI apiURI = new URI(apiUrl);
    117             final URL rfc8414URL = new URI(apiURI.getScheme(), apiURI.getHost(),
    118                     "/.well-known/oauth-authorization-server", null).toURL();
     181            // keep the port, as for a development server on http://localhost:3000
     182            final URL rfc8414URL = new URI(apiURI.getScheme(), null, apiURI.getHost(), apiURI.getPort(),
     183                    "/.well-known/oauth-authorization-server", null, null).toURL();
    119184            client = HttpClient.create(rfc8414URL);
    120185            HttpClient.Response response = client.connect();
    121186            if (response.getResponseCode() == 200) {
    … … public final class OAuthParameters {  
    146211        final String clientId;
    147212        final String clientSecret;
    148213        final String redirectUri = "http://127.0.0.1:8111/oauth_authorization";
    149         final String baseUrl;
    150214        apiUrl = OsmApi.normalizeApiUrl(apiUrl == null ? OsmApi.getOsmApi().getServerUrl() : apiUrl);
    151215        switch (apiUrl) {
    152216            case OSM_API_DEV:
    … … public final class OAuthParameters {  
    180244                clientId = "";
    181245                clientSecret = null;
    182246        }
    183         baseUrl = apiUrl;
    184247        // Check if the server is RFC 8414 compliant
    185248        try {
    186249            synchronized (RFC8414_RESPONSES) {
    … … public final class OAuthParameters {  
    207270        } catch (OAuthException e) {
    208271            Logging.trace(e);
    209272        }
    210         // Fall back to guessing the parameters.
    211         return new OAuth20Parameters(clientId, clientSecret, baseUrl, apiUrl, redirectUri);
     273        // Fall back to the endpoints of openstreetmap-website, which is what OSM API servers run
     274        return new OAuth20Parameters(clientId, clientSecret, getWebsite(apiUrl) + "/oauth2", apiUrl, redirectUri);
     275    }
     276
     277    /**
     278     * Get the website of an OSM API server, where openstreetmap-website has its OAuth 2.0 endpoints: the API URL
     279     * without its {@code /api}, except for the default OSM API, which is served from a host of its own.
     280     * @param apiUrl The normalized API URL
     281     * @return The website URL
     282     */
     283    private static String getWebsite(String apiUrl) {
     284        if (OSM_API_DEFAULT.equals(apiUrl)) {
     285            return Config.getUrls().getOSMWebsite();
     286        }
     287        return apiUrl.replaceAll("/api$", "");
    212288    }
    213289
    214290    /**
    … … public final class OAuthParameters {  
    230306    }
    231307
    232308    /**
    233      * Replies a set of parameters as defined in the preferences.
     309     * Replies a set of parameters as defined in the preferences: the parameters of the access token of the server,
     310     * otherwise the parameters the user entered, unless the server is set to {@link #isUseDefault(String) use the
     311     * default parameters}, otherwise the {@link #createDefault(String, OAuthVersion) default parameters}.
    234312     *
    235313     * @param oAuthVersion The OAuth version to use.
    236314     * @param apiUrl the API URL. Must not be {@code null}.
    … … public final class OAuthParameters {  
    239317     */
    240318    public static IOAuthParameters createFromApiUrl(String apiUrl, OAuthVersion oAuthVersion) {
    241319        apiUrl = OsmApi.normalizeApiUrl(apiUrl);
    242         final String originalApiUrl = apiUrl;
    243320        // We actually need the host
    244         if (apiUrl.startsWith("https://") || apiUrl.startsWith("http://")) {
    245             try {
    246                 apiUrl = new URI(apiUrl).getHost();
    247             } catch (URISyntaxException syntaxException) {
    248                 Logging.trace(apiUrl);
    249             }
    250         }
     321        final String host = getHost(apiUrl);
    251322        switch (oAuthVersion) {
    252323            case OAuth20:
    253324            case OAuth21: // Right now, OAuth 2.1 will work with our OAuth 2.0 implementation
    254325                try {
    255                     IOAuthToken storedToken = CredentialsManager.getInstance().lookupOAuthAccessToken(apiUrl);
     326                    IOAuthToken storedToken = CredentialsManager.getInstance().lookupOAuthAccessToken(host);
    256327                    if (storedToken != null) {
    257328                        return storedToken.getParameters();
    258329                    }
    259330                } catch (CredentialsAgentException e) {
    260331                    Logging.trace(e);
    261332                }
    262                 IOAuthParameters remembered = createFromPreferences(originalApiUrl, apiUrl);
    263                 if (remembered != null) {
    264                     return remembered;
     333                if (!isUseDefault(apiUrl)) {
     334                    // the API URL is where earlier versions of JOSM stored them
     335                    IOAuthParameters remembered = createFromPreferences(host, apiUrl);
     336                    if (remembered != null) {
     337                        return remembered;
     338                    }
    265339                }
    266                 // Use the URL as it was given: apiUrl is the host by now, which is never a valid URL, so
    267                 // createDefault() would silently fall back to the API currently configured in the preferences.
    268                 return createDefault(originalApiUrl, oAuthVersion);
     340                // Use the URL as it was given: the host is never a valid URL, so createDefault() would silently
     341                // fall back to the API currently configured in the preferences.
     342                return createDefault(apiUrl, oAuthVersion);
    269343            default:
    270344                throw new IllegalArgumentException("Unknown OAuth version: " + oAuthVersion);
    271345        }
  • deleted file src/org/openstreetmap/josm/data/oauth/OsmPrivileges.java

    diff --git src/org/openstreetmap/josm/data/oauth/OsmPrivileges.java src/org/openstreetmap/josm/data/oauth/OsmPrivileges.java
    deleted file mode 100644
    index 332f788cc8..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.data.oauth;
    3 
    4 /**
    5  * List of permissions granted to the current OSM connection.
    6  * @since 2747
    7  */
    8 public class OsmPrivileges {
    9     private boolean allowWriteApi;
    10     private boolean allowWriteGpx;
    11     private boolean allowReadGpx;
    12     private boolean allowReadPrefs;
    13     private boolean allowWritePrefs;
    14     private boolean allowModifyNotes;
    15     private boolean allowWriteDiary;
    16 
    17     /**
    18      * Determines if the client is allowed to modify the map.
    19      * @return {@code true} if the client is allowed to modify the map, {@code false} otherwise
    20      */
    21     public boolean isAllowWriteApi() {
    22         return allowWriteApi;
    23     }
    24 
    25     /**
    26      * Sets whether the client is allowed to modify the map.
    27      * @param allowWriteApi {@code true} if the client is allowed to modify the map, {@code false} otherwise
    28      */
    29     public void setAllowWriteApi(boolean allowWriteApi) {
    30         this.allowWriteApi = allowWriteApi;
    31     }
    32 
    33     /**
    34      * Determines if the client is allowed to upload GPS traces.
    35      * @return {@code true} if the client is allowed to upload GPS traces, {@code false} otherwise
    36      */
    37     public boolean isAllowWriteGpx() {
    38         return allowWriteGpx;
    39     }
    40 
    41     /**
    42      * Sets whether the client is allowed to upload GPS traces.
    43      * @param allowWriteGpx {@code true} if the client is allowed to upload GPS traces, {@code false} otherwise
    44      */
    45     public void setAllowWriteGpx(boolean allowWriteGpx) {
    46         this.allowWriteGpx = allowWriteGpx;
    47     }
    48 
    49     /**
    50      * Determines if the client is allowed to read private GPS traces.
    51      * @return {@code true} if the client is allowed to read private GPS traces, {@code false} otherwise
    52      */
    53     public boolean isAllowReadGpx() {
    54         return allowReadGpx;
    55     }
    56 
    57     /**
    58      * Sets whether the client is allowed to read private GPS traces.
    59      * @param allowReadGpx {@code true} if the client is allowed to read private GPS traces, {@code false} otherwise
    60      */
    61     public void setAllowReadGpx(boolean allowReadGpx) {
    62         this.allowReadGpx = allowReadGpx;
    63     }
    64 
    65     /**
    66      * Determines if the client is allowed to read user preferences.
    67      * @return {@code true} if the client is allowed to read user preferences, {@code false} otherwise
    68      */
    69     public boolean isAllowReadPrefs() {
    70         return allowReadPrefs;
    71     }
    72 
    73     /**
    74      * Sets whether the client is allowed to read user preferences.
    75      * @param allowReadPrefs {@code true} if the client is allowed to read user preferences, {@code false} otherwise
    76      */
    77     public void setAllowReadPrefs(boolean allowReadPrefs) {
    78         this.allowReadPrefs = allowReadPrefs;
    79     }
    80 
    81     /**
    82      * Determines if the client is allowed to modify user preferences.
    83      * @return {@code true} if the client is allowed to modify user preferences, {@code false} otherwise
    84      */
    85     public boolean isAllowWritePrefs() {
    86         return allowWritePrefs;
    87     }
    88 
    89     /**
    90      * Sets whether the client is allowed to modify user preferences.
    91      * @param allowWritePrefs {@code true} if the client is allowed to modify user preferences, {@code false} otherwise
    92      */
    93     public void setAllowWritePrefs(boolean allowWritePrefs) {
    94         this.allowWritePrefs = allowWritePrefs;
    95     }
    96 
    97     /**
    98      * Determines if the client is allowed to modify notes.
    99      * @return {@code true} if the client is allowed to modify notes, {@code false} otherwise
    100      */
    101     public boolean isAllowModifyNotes() {
    102         return allowModifyNotes;
    103     }
    104 
    105     /**
    106      * Sets whether the client is allowed to modify notes.
    107      * @param allowModifyNotes {@code true} if the client is allowed to modify notes, {@code false} otherwise
    108      */
    109     public void setAllowModifyNotes(boolean allowModifyNotes) {
    110         this.allowModifyNotes = allowModifyNotes;
    111     }
    112 
    113     /**
    114      * Determines if the client is allowed to write diary.
    115      * @return {@code true} if the client is allowed to write diary, {@code false} otherwise
    116      * @since 17972
    117      */
    118     public boolean isAllowWriteDiary() {
    119         return allowWriteDiary;
    120     }
    121 
    122     /**
    123      * Sets whether the client is allowed to write diary.
    124      * @param allowWriteDiary {@code true} if the client is allowed to write diary, {@code false} otherwise
    125      * @since 17972
    126      */
    127     public void setAllowWriteDiary(boolean allowWriteDiary) {
    128         this.allowWriteDiary = allowWriteDiary;
    129     }
    130 }
  • src/org/openstreetmap/josm/data/oauth/osm/OsmScopes.java

    diff --git src/org/openstreetmap/josm/data/oauth/osm/OsmScopes.java src/org/openstreetmap/josm/data/oauth/osm/OsmScopes.java
    index aacdf2e6fe..14dff14660 100644
    public enum OsmScopes {  
    2020    /** Upload GPS traces */
    2121    write_gpx,
    2222    /** Modify notes */
    23     write_notes
     23    write_notes;
     24
     25    /**
     26     * Get the scopes JOSM requests when it is authorized. An OAuth 2.0 application which JOSM is to use must be
     27     * registered with at least these.
     28     * @return the scopes, in the order they are requested
     29     * @since xxx
     30     */
     31    public static OsmScopes[] getJosmScopes() {
     32        return new OsmScopes[] {read_gpx, write_gpx, read_prefs, write_prefs, write_api, write_notes};
     33    }
    2434}
  • src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java

    diff --git src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java
    index 2aec87957c..62b25af769 100644
    import java.util.regex.Pattern;  
    1515
    1616import javax.swing.JOptionPane;
    1717
     18import org.openstreetmap.josm.actions.PreferencesAction;
    1819import org.openstreetmap.josm.data.osm.OsmPrimitive;
     20import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
     21import org.openstreetmap.josm.gui.preferences.server.ServerAccessPreference;
    1922import org.openstreetmap.josm.io.ChangesetClosedException;
    2023import org.openstreetmap.josm.io.IllegalDataException;
    2124import org.openstreetmap.josm.io.MissingOAuthAccessTokenException;
    … … import org.openstreetmap.josm.io.OsmApiException;  
    2528import org.openstreetmap.josm.io.OsmApiInitializationException;
    2629import org.openstreetmap.josm.io.OsmTransferException;
    2730import org.openstreetmap.josm.tools.ExceptionUtil;
     31import org.openstreetmap.josm.tools.ImageProvider;
    2832import org.openstreetmap.josm.tools.Logging;
    2933import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
    3034
    … … public final class ExceptionDialogUtil {  
    368372     * @param e the exception
    369373     */
    370374    public static void explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) {
    371         showErrorDialog(
     375        final ButtonSpec[] buttons = {
     376                new ButtonSpec(tr("Open preferences"), new ImageProvider("preference"),
     377                        tr("Open the OSM server preferences, to authorize JOSM or to enter an Access Token"), null),
     378                new ButtonSpec(tr("Close"), new ImageProvider("cancel"), tr("Close this message"), null)
     379        };
     380        final int answer = HelpAwareOptionPane.showOptionDialog(
     381                MainApplication.getMainFrame(),
    372382                ExceptionUtil.explainMissingOAuthAccessTokenException(e),
    373383                tr("Authentication failed"),
     384                JOptionPane.ERROR_MESSAGE,
     385                null,
     386                buttons,
     387                buttons[0],
    374388                ht("/ErrorMessages#MissingOAuthAccessToken")
    375389        );
     390        if (answer == 0) {
     391            PreferencesAction.forPreferenceTab(tr("Preferences"), null, ServerAccessPreference.class).run();
     392        }
    376393    }
    377394
    378395    /**
  • src/org/openstreetmap/josm/gui/MainApplication.java

    diff --git src/org/openstreetmap/josm/gui/MainApplication.java src/org/openstreetmap/josm/gui/MainApplication.java
    index 9cdc48cc57..f2eecbf110 100644
    import org.openstreetmap.josm.gui.layer.MainLayerManager;  
    119119import org.openstreetmap.josm.gui.layer.OsmDataLayer;
    120120import org.openstreetmap.josm.gui.mappaint.RenderingCLI;
    121121import org.openstreetmap.josm.gui.mappaint.loader.MapPaintStyleLoader;
    122 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    123122import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
    124123import org.openstreetmap.josm.gui.preferences.display.LafPreference;
    125124import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
    … … import org.openstreetmap.josm.io.FileWatcher;  
    139138import org.openstreetmap.josm.io.MessageNotifier;
    140139import org.openstreetmap.josm.io.NetworkManager;
    141140import org.openstreetmap.josm.io.OnlineResource;
    142 import org.openstreetmap.josm.io.OsmConnection;
    143141import org.openstreetmap.josm.io.OsmTransferException;
    144142import org.openstreetmap.josm.io.auth.AbstractCredentialsAgent;
    145143import org.openstreetmap.josm.io.auth.CredentialsManager;
    … … public class MainApplication {  
    11101108
    11111109    static void setupCallbacks() {
    11121110        HttpClient.setFactory(Http1Client::new);
    1113         OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
    11141111        AbstractCredentialsAgent.setCredentialsProvider(CredentialDialog::promptCredentials);
    11151112        MessageNotifier.setNotifierCallback(MainApplication::notifyNewMessages);
    11161113        DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
  • deleted file src/org/openstreetmap/josm/gui/oauth/AbstractAuthorizationUI.java

    diff --git src/org/openstreetmap/josm/gui/oauth/AbstractAuthorizationUI.java src/org/openstreetmap/josm/gui/oauth/AbstractAuthorizationUI.java
    deleted file mode 100644
    index 24d3d2d3e1..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import java.util.Objects;
    5 
    6 import org.openstreetmap.josm.data.oauth.IOAuthParameters;
    7 import org.openstreetmap.josm.data.oauth.IOAuthToken;
    8 import org.openstreetmap.josm.data.oauth.OAuthParameters;
    9 import org.openstreetmap.josm.data.oauth.OAuthVersion;
    10 import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
    11 import org.openstreetmap.josm.tools.CheckParameterUtil;
    12 
    13 /**
    14  * This is the abstract base class for the three authorisation UIs.
    15  *
    16  * @since 2746
    17  */
    18 public abstract class AbstractAuthorizationUI extends VerticallyScrollablePanel {
    19     /**
    20      * The property name for the Access Token property
    21      */
    22     public static final String ACCESS_TOKEN_PROP = AbstractAuthorizationUI.class.getName() + ".accessToken";
    23 
    24     private String apiUrl;
    25     private final AdvancedOAuthPropertiesPanel pnlAdvancedProperties;
    26     private transient IOAuthToken accessToken;
    27 
    28     /**
    29      * Constructs a new {@code AbstractAuthorizationUI} for the given API URL.
    30      * @param apiUrl The OSM API URL (may be null)
    31      * @param oAuthVersion The oauth version to use
    32      * @since 18991
    33      */
    34     protected AbstractAuthorizationUI(String apiUrl, OAuthVersion oAuthVersion) {
    35         this.pnlAdvancedProperties = new AdvancedOAuthPropertiesPanel(oAuthVersion);
    36         if (apiUrl != null) {
    37             setApiUrl(apiUrl);
    38         }
    39     }
    40 
    41     protected void fireAccessTokenChanged(IOAuthToken oldValue, IOAuthToken newValue) {
    42         firePropertyChange(ACCESS_TOKEN_PROP, oldValue, newValue);
    43     }
    44 
    45     /**
    46      * Replies the URL of the OSM API for which this UI is currently trying to retrieve an OAuth
    47      * Access Token
    48      *
    49      * @return the API URL
    50      */
    51     public String getApiUrl() {
    52         return apiUrl;
    53     }
    54 
    55     /**
    56      * Sets the URL of the OSM API for which this UI is currently trying to retrieve an OAuth
    57      * Access Token
    58      *
    59      * @param apiUrl the api URL
    60      */
    61     public void setApiUrl(String apiUrl) {
    62         this.apiUrl = apiUrl;
    63         this.pnlAdvancedProperties.setApiUrl(apiUrl);
    64     }
    65 
    66     /**
    67      * Replies the panel for entering advanced OAuth parameters (see {@link OAuthParameters})
    68      *
    69      * @return the panel for entering advanced OAuth parameters
    70      * @see #getOAuthParameters()
    71      */
    72     protected AdvancedOAuthPropertiesPanel getAdvancedPropertiesPanel() {
    73         return pnlAdvancedProperties;
    74     }
    75 
    76     /**
    77      * Replies the current set of advanced OAuth parameters in this UI
    78      *
    79      * @return the current set of advanced OAuth parameters in this UI
    80      */
    81     public IOAuthParameters getOAuthParameters() {
    82         return pnlAdvancedProperties.getAdvancedParameters();
    83     }
    84 
    85     /**
    86      * Replies the retrieved Access Token. null, if no Access Token was retrieved.
    87      *
    88      * @return the retrieved Access Token
    89      */
    90     public IOAuthToken getAccessToken() {
    91         return accessToken;
    92     }
    93 
    94     /**
    95      * Sets the current Access Token. This will fire a property change event for {@link #ACCESS_TOKEN_PROP}
    96      * if the access token has changed
    97      *
    98      * @param accessToken the new access token. null, to clear the current access token
    99      */
    100     protected void setAccessToken(IOAuthToken accessToken) {
    101         IOAuthToken oldValue = this.accessToken;
    102         this.accessToken = accessToken;
    103         if (oldValue == null ^ this.accessToken == null) {
    104             fireAccessTokenChanged(oldValue, this.accessToken);
    105         } else if (oldValue == null && this.accessToken == null) {
    106             // no change - don't fire an event
    107         } else if (!Objects.equals(oldValue, this.accessToken)) {
    108             fireAccessTokenChanged(oldValue, this.accessToken);
    109         }
    110     }
    111 
    112     /**
    113      * Get the OAuth version for this AuthorizationUI
    114      * @return The OAuth version
    115      * @since 18991
    116      */
    117     public OAuthVersion getOAuthVersion() {
    118         return this.pnlAdvancedProperties.getAdvancedParameters().getOAuthVersion();
    119     }
    120 
    121     /**
    122      * Replies true if this UI currently has an Access Token
    123      *
    124      * @return true if this UI currently has an Access Token
    125      */
    126     public boolean hasAccessToken() {
    127         return accessToken != null;
    128     }
    129 
    130     /**
    131      * Replies whether the user has chosen to save the Access Token in the JOSM
    132      * preferences or not.
    133      *
    134      * @return true if the user has chosen to save the Access Token
    135      */
    136     public abstract boolean isSaveAccessTokenToPreferences();
    137 
    138     /**
    139      * Initializes the authorisation UI.
    140      *
    141      * @param paramApiUrl the API URL. Must not be null.
    142      * @throws IllegalArgumentException if paramApiUrl is null
    143      */
    144     public void initialize(String paramApiUrl) {
    145         CheckParameterUtil.ensureParameterNotNull(paramApiUrl, "paramApiUrl");
    146         pnlAdvancedProperties.initialize(paramApiUrl);
    147     }
    148 }
  • deleted file src/org/openstreetmap/josm/gui/oauth/AccessTokenInfoPanel.java

    diff --git src/org/openstreetmap/josm/gui/oauth/AccessTokenInfoPanel.java src/org/openstreetmap/josm/gui/oauth/AccessTokenInfoPanel.java
    deleted file mode 100644
    index bc4098dfbc..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 import java.awt.GridBagConstraints;
    7 import java.awt.GridBagLayout;
    8 import java.awt.Insets;
    9 
    10 import javax.swing.JCheckBox;
    11 import javax.swing.JLabel;
    12 import javax.swing.JPanel;
    13 
    14 import org.openstreetmap.josm.data.oauth.IOAuthToken;
    15 import org.openstreetmap.josm.data.oauth.OAuth20Token;
    16 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    17 import org.openstreetmap.josm.gui.widgets.JosmTextField;
    18 import org.openstreetmap.josm.tools.JosmRuntimeException;
    19 
    20 /**
    21  * Displays the key of an OAuth Access Token.
    22  * @since 2746 (modified for OAuth 2 in 18991)
    23  */
    24 public class AccessTokenInfoPanel extends JPanel {
    25 
    26     private final JosmTextField tfAccessTokenKey = new JosmTextField(null, null, 0, false);
    27     private final JCheckBox cbSaveAccessTokenInPreferences = new JCheckBox(tr("Save Access Token in preferences"));
    28 
    29     /**
    30      * Constructs a new {@code AccessTokenInfoPanel}.
    31      */
    32     public AccessTokenInfoPanel() {
    33         build();
    34     }
    35 
    36     protected final void build() {
    37         setLayout(new GridBagLayout());
    38         GridBagConstraints gc = new GridBagConstraints();
    39 
    40         // the access token key
    41         gc.anchor = GridBagConstraints.NORTHWEST;
    42         gc.fill = GridBagConstraints.HORIZONTAL;
    43         gc.weightx = 0.0;
    44         gc.insets = new Insets(0, 0, 3, 3);
    45         add(new JLabel(tr("Access Token Key:")), gc);
    46 
    47         gc.gridx = 1;
    48         gc.weightx = 1.0;
    49         add(tfAccessTokenKey, gc);
    50         tfAccessTokenKey.setEditable(false);
    51 
    52         // the access token secret
    53         gc.gridx = 0;
    54         gc.gridy = 1;
    55         gc.weightx = 0.0;
    56         gc.insets = new Insets(0, 0, 3, 3);
    57         add(new JLabel(tr("Access Token Secret:")), gc);
    58 
    59         gc.weightx = 1.0;
    60         // the checkbox
    61         gc.gridx = 0;
    62         gc.gridy = 2;
    63         gc.gridwidth = 2;
    64         add(cbSaveAccessTokenInPreferences, gc);
    65         cbSaveAccessTokenInPreferences.setToolTipText(tr(
    66                 "<html>Select to save the Access Token in the JOSM preferences.<br>"
    67                 + "Unselect to use the Access Token in this JOSM session only.</html>"
    68         ));
    69         cbSaveAccessTokenInPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences());
    70 
    71         // filler - grab the remaining space
    72         gc.gridx = 0;
    73         gc.gridy = 3;
    74         gc.weightx = 1.0;
    75         gc.weighty = 1.0;
    76         gc.fill = GridBagConstraints.BOTH;
    77         gc.gridwidth = 2;
    78         add(new JPanel(), gc);
    79     }
    80 
    81     /**
    82      * Displays the key and secret in <code>token</code>.
    83      *
    84      * @param token the access  token. If null, the content in the info panel is cleared
    85      */
    86     public void setAccessToken(IOAuthToken token) {
    87         if (token == null) {
    88             tfAccessTokenKey.setText("");
    89             return;
    90         }
    91         if (token instanceof OAuth20Token) {
    92             tfAccessTokenKey.setText(((OAuth20Token) token).getBearerToken());
    93         } else {
    94             throw new JosmRuntimeException("Unknown token type: " + token.getClass());
    95         }
    96     }
    97 
    98     public void setSaveToPreferences(boolean saveToPreferences) {
    99         cbSaveAccessTokenInPreferences.setSelected(saveToPreferences);
    100     }
    101 
    102     public boolean isSaveToPreferences() {
    103         return cbSaveAccessTokenInPreferences.isSelected();
    104     }
    105 }
  • src/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanel.java

    diff --git src/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanel.java src/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanel.java
    index 063cc62c0d..7bccca48e4 100644
    import java.awt.GridBagLayout;  
    99import java.awt.Insets;
    1010import java.awt.event.ItemEvent;
    1111import java.awt.event.ItemListener;
     12import java.util.Objects;
     13import java.util.stream.Collectors;
     14import java.util.stream.Stream;
    1215
    1316import javax.swing.BorderFactory;
    1417import javax.swing.JCheckBox;
     18import javax.swing.JComponent;
    1519import javax.swing.JLabel;
    1620import javax.swing.JOptionPane;
    1721import javax.swing.event.DocumentEvent;
    … … import org.openstreetmap.josm.data.oauth.IOAuthParameters;  
    2125import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
    2226import org.openstreetmap.josm.data.oauth.OAuthParameters;
    2327import org.openstreetmap.josm.data.oauth.OAuthVersion;
     28import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
    2429import org.openstreetmap.josm.gui.HelpAwareOptionPane;
    2530import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
    2631import org.openstreetmap.josm.gui.MainApplication;
    … … import org.openstreetmap.josm.gui.util.GuiHelper;  
    2934import org.openstreetmap.josm.gui.widgets.JosmTextField;
    3035import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
    3136import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
    32 import org.openstreetmap.josm.spi.preferences.Config;
    3337import org.openstreetmap.josm.tools.CheckParameterUtil;
    3438import org.openstreetmap.josm.tools.ImageProvider;
    3539
    3640/**
    3741 * Panel allowing the user to setup advanced OAuth parameters:
    3842 * <ul>
    39  * <li>Consumer key</li>
    40  * <li>Consumer secret</li>
    41  * <li>Request token URL</li>
     43 * <li>Client ID</li>
     44 * <li>Client secret</li>
     45 * <li>Redirect URI</li>
    4246 * <li>Access token URL</li>
    4347 * <li>Authorize URL</li>
    44  * <li>OSM login URL</li>
    45  * <li>OSM logout URL</li>
     48 * <li>Access token, which can be pasted instead of authorizing JOSM</li>
    4649 * </ul>
    4750 *
    4851 * @see OAuthParameters
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    5760    public static final String PARAMETERS_CHANGED_PROP = AdvancedOAuthPropertiesPanel.class.getName() + ".parametersChanged";
    5861
    5962    private final JCheckBox cbUseDefaults = new JCheckBox(tr("Use default settings"));
    60     private final JosmTextField tfConsumerKey = new JosmTextField();
    61     private final JosmTextField tfConsumerSecret = new JosmTextField();
    62     private final JosmTextField tfRequestTokenURL = new JosmTextField();
     63    private final JosmTextField tfClientId = new JosmTextField();
     64    private final JosmTextField tfClientSecret = new JosmTextField();
     65    private final JosmTextField tfRedirectUri = new JosmTextField();
    6366    private final JosmTextField tfAccessTokenURL = new JosmTextField();
    6467    private final JosmTextField tfAuthoriseURL = new JosmTextField();
     68    private final JLabel lblAccessToken = new JLabel(tr("Access Token:"));
     69    private final JosmTextField tfAccessToken = new JosmTextField();
    6570    private final OAuthVersion oauthVersion;
    6671    private transient UseDefaultItemListener ilUseDefault;
    6772    private String apiUrl;
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    8792        gc.gridwidth = 3;
    8893        add(cbUseDefaults, gc);
    8994
    90         // -- consumer key
     95        // -- client id
    9196        gc.gridy = 1;
    9297        gc.weightx = 0.0;
    9398        gc.gridwidth = 1;
    94         add(new JLabel(tr("Client ID:")), gc);
     99        add(label(tr("Client ID:"), tfClientId), gc);
    95100
    96101        gc.gridx = 1;
    97102        gc.weightx = 1.0;
    98         add(tfConsumerKey, gc);
    99         SelectAllOnFocusGainedDecorator.decorate(tfConsumerKey);
     103        add(tfClientId, gc);
     104        SelectAllOnFocusGainedDecorator.decorate(tfClientId);
    100105
    101         // -- consumer secret
     106        // -- client secret
    102107        gc.gridy++;
    103108        gc.gridx = 0;
    104109        gc.weightx = 0.0;
    105         add(new JLabel(tr("Client Secret:")), gc);
     110        add(label(tr("Client Secret:"), tfClientSecret), gc);
    106111
    107112        gc.gridx = 1;
    108113        gc.weightx = 1.0;
    109         add(tfConsumerSecret, gc);
    110         SelectAllOnFocusGainedDecorator.decorate(tfConsumerSecret);
     114        add(tfClientSecret, gc);
     115        SelectAllOnFocusGainedDecorator.decorate(tfClientSecret);
    111116
    112         // -- request token URL
     117        // -- redirect URI
    113118        gc.gridy++;
    114119        gc.gridx = 0;
    115120        gc.weightx = 0.0;
    116         add(new JLabel(tr("Redirect URL:")), gc);
     121        add(label(tr("Redirect URL:"), tfRedirectUri), gc);
    117122
    118123        gc.gridx = 1;
    119124        gc.weightx = 1.0;
    120         add(tfRequestTokenURL, gc);
    121         SelectAllOnFocusGainedDecorator.decorate(tfRequestTokenURL);
     125        add(tfRedirectUri, gc);
     126        SelectAllOnFocusGainedDecorator.decorate(tfRedirectUri);
    122127
    123128        // -- access token URL
    124129        gc.gridy++;
    125130        gc.gridx = 0;
    126131        gc.weightx = 0.0;
    127         add(new JLabel(tr("Access Token URL:")), gc);
     132        add(label(tr("Access Token URL:"), tfAccessTokenURL), gc);
    128133
    129134        gc.gridx = 1;
    130135        gc.weightx = 1.0;
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    135140        gc.gridy++;
    136141        gc.gridx = 0;
    137142        gc.weightx = 0.0;
    138         add(new JLabel(tr("Authorize URL:")), gc);
     143        add(label(tr("Authorize URL:"), tfAuthoriseURL), gc);
    139144
    140145        gc.gridx = 1;
    141146        gc.weightx = 1.0;
    142147        add(tfAuthoriseURL, gc);
    143148        SelectAllOnFocusGainedDecorator.decorate(tfAuthoriseURL);
    144149
     150        // -- access token: not one of the settings, so it can be pasted whether or not they are the default ones
     151        gc.gridy++;
     152        gc.gridx = 0;
     153        gc.weightx = 0.0;
     154        lblAccessToken.setLabelFor(tfAccessToken);
     155        add(lblAccessToken, gc);
     156
     157        gc.gridx = 1;
     158        gc.weightx = 1.0;
     159        add(tfAccessToken, gc);
     160        SelectAllOnFocusGainedDecorator.decorate(tfAccessToken);
     161
     162        setToolTips();
     163
    145164        ilUseDefault = new UseDefaultItemListener();
    146165        cbUseDefaults.addItemListener(ilUseDefault);
    147         cbUseDefaults.setSelected(Config.getPref().getBoolean("oauth.settings.use-default", true));
     166        cbUseDefaults.setSelected(true);
     167        setChildComponentsVisible(false);
    148168        cbUseDefaults.addItemListener(e -> fireParametersChanged());
    149         tfConsumerKey.getDocument().addDocumentListener(new DocumentListener() {
     169        tfClientId.getDocument().addDocumentListener(new DocumentListener() {
    150170            @Override
    151171            public void insertUpdate(DocumentEvent e) {
    152172                fireParametersChanged();
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    164184        });
    165185    }
    166186
     187    /**
     188     * Creates the label of a field, which has the tool tip of the field.
     189     * @param text the text of the label
     190     * @param field the field
     191     * @return the label
     192     */
     193    private static JLabel label(String text, JosmTextField field) {
     194        final JLabel label = new JLabel(text);
     195        label.setLabelFor(field);
     196        return label;
     197    }
     198
     199    /**
     200     * Explains each field, for the fields and their labels.
     201     */
     202    private void setToolTips() {
     203        final String scopes = Stream.of(OsmScopes.getJosmScopes()).map(Enum::name).collect(Collectors.joining(", "));
     204        cbUseDefaults.setToolTipText(tr("<html>Use the OAuth settings JOSM has built in for this server, or which the server publishes.<br>"
     205                + "Untick to enter the settings of an OAuth 2.0 application you registered on the server yourself.</html>"));
     206        tfClientId.setToolTipText(tr("<html>The Client ID of an OAuth 2.0 application registered on this server.<br>"
     207                + "On an openstreetmap-website server, register one under My Settings &gt; OAuth 2 applications,<br>"
     208                + "with the redirect URL below and the permissions {0}.</html>", scopes));
     209        tfClientSecret.setToolTipText(tr("<html>Only needed if the application is registered as confidential.<br>"
     210                + "The applications JOSM has built in are public clients and have none.</html>"));
     211        tfRedirectUri.setToolTipText(tr("<html>Must be exactly the redirect URL registered with the application.<br>"
     212                + "JOSM receives the authorization at {0}, by remote control.</html>", "http://127.0.0.1:8111/oauth_authorization"));
     213        tfAccessTokenURL.setToolTipText(tr("<html>Where JOSM gets the Access Token from.<br>"
     214                + "Taken from the OAuth metadata of the server if it publishes any; on an openstreetmap-website server,<br>"
     215                + "this is the address of the website followed by {0}, not the API URL.</html>", "/oauth2/token"));
     216        tfAuthoriseURL.setToolTipText(tr("<html>Where the web browser is sent to authorize JOSM.<br>"
     217                + "Taken from the OAuth metadata of the server if it publishes any; on an openstreetmap-website server,<br>"
     218                + "this is the address of the website followed by {0}, not the API URL.</html>", "/oauth2/authorize"));
     219        tfAccessToken.setToolTipText(tr("<html>The Access Token JOSM uses for this server.<br>"
     220                + "A token issued outside JOSM can be pasted here instead of authorizing JOSM; it needs the permissions {0}.</html>",
     221                scopes));
     222        for (Component c : getComponents()) {
     223            if (c instanceof JLabel && ((JLabel) c).getLabelFor() instanceof JComponent) {
     224                ((JLabel) c).setToolTipText(((JComponent) ((JLabel) c).getLabelFor()).getToolTipText());
     225            }
     226        }
     227    }
     228
    167229    private void fireParametersChanged() {
    168230        firePropertyChange(PARAMETERS_CHANGED_PROP, null, null);
    169231    }
    170232
     233    /**
     234     * Get the access token as entered in the panel.
     235     * @return the access token, without surrounding white space; empty if there is none
     236     * @since xxx
     237     */
     238    public String getAccessToken() {
     239        return tfAccessToken.getText().trim();
     240    }
     241
     242    /**
     243     * Sets the access token to be displayed.
     244     * @param accessToken the access token, or {@code null} if there is none
     245     * @since xxx
     246     */
     247    public void setAccessToken(String accessToken) {
     248        tfAccessToken.setText(accessToken);
     249    }
     250
    171251    /**
    172252     * Determines if the panel is set to use the default parameters for the API URL rather than
    173253     * the values entered in its fields.
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    180260
    181261    /**
    182262     * Get the client id as entered in the panel, without falling back to the defaults.
    183      * @return the client id field's text
     263     * @return the client id field's text, without surrounding white space
    184264     * @since 19627
    185265     */
    186266    public String getEnteredClientId() {
    187         return tfConsumerKey.getText();
     267        return tfClientId.getText().trim();
    188268    }
    189269
    190270    protected boolean hasCustomSettings() {
    191         IOAuthParameters params = OAuthParameters.createDefault(apiUrl, OAuthVersion.OAuth20);
     271        IOAuthParameters params = OAuthParameters.createDefault(apiUrl, this.oauthVersion);
    192272        return !params.equals(getAdvancedParameters());
    193273    }
    194274
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    230310                        case OAuth20:
    231311                        case OAuth21:
    232312                            OAuth20Parameters params20 = (OAuth20Parameters) iParams;
    233                             tfConsumerKey.setText(params20.getClientId());
    234                             tfConsumerSecret.setText(params20.getClientSecret());
     313                            tfClientId.setText(params20.getClientId());
     314                            tfClientSecret.setText(params20.getClientSecret());
    235315                            tfAccessTokenURL.setText(params20.getAccessTokenUrl());
    236316                            tfAuthoriseURL.setText(params20.getAuthorizationUrl());
    237                             tfRequestTokenURL.setText(params20.getRedirectUri());
     317                            tfRedirectUri.setText(params20.getRedirectUri());
    238318                            break;
    239319                        default:
    240320                            throw new UnsupportedOperationException("Unsupported OAuth version: " + this.oauthVersion);
    241321                    }
    242                     setChildComponentsEnabled(false);
     322                    setChildComponentsVisible(false);
    243323                });
    244324    }
    245325
    246     protected void setChildComponentsEnabled(boolean enabled) {
     326    /**
     327     * Shows or hides the OAuth parameters: they are shown when the user enters them, that is when the default
     328     * settings are not used. The access token is not one of them, and is always shown.
     329     * @param visible {@code true} to show the parameters
     330     * @since xxx
     331     */
     332    protected void setChildComponentsVisible(boolean visible) {
    247333        for (Component c: getComponents()) {
     334            if (c == tfAccessToken || c == lblAccessToken) {
     335                continue;
     336            }
    248337            if (c instanceof JosmTextField || c instanceof JLabel) {
    249                 c.setEnabled(enabled);
     338                c.setVisible(visible);
    250339            }
    251340        }
     341        revalidate();
    252342    }
    253343
    254344    /**
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    259349    public IOAuthParameters getAdvancedParameters() {
    260350        if (cbUseDefaults.isSelected())
    261351            return OAuthParameters.createDefault(apiUrl, this.oauthVersion);
     352        return getDisplayedParameters();
     353    }
     354
     355    /**
     356     * Replies the OAuth parameters as currently displayed in this properties panel: the default ones are shown when
     357     * "use default settings" is ticked, as far as they are known yet. Unlike {@link #getAdvancedParameters()}, this
     358     * never makes a network request, and some of the parameters may be empty. White space around the values, which
     359     * is easily copied along with them, is left out: a client secret with a trailing space is refused by the server.
     360     *
     361     * @return the OAuth parameters
     362     * @since xxx
     363     */
     364    public OAuth20Parameters getDisplayedParameters() {
    262365        return new OAuth20Parameters(
    263                 tfConsumerKey.getText(),
    264                 tfConsumerSecret.getText(),
    265                 tfAccessTokenURL.getText(),
    266                 tfAuthoriseURL.getText(),
     366                tfClientId.getText().trim(),
     367                tfClientSecret.getText().trim(),
     368                tfAccessTokenURL.getText().trim(),
     369                tfAuthoriseURL.getText().trim(),
    267370                apiUrl,
    268                 tfRequestTokenURL.getText()
     371                tfRedirectUri.getText().trim()
    269372                );
    270373    }
    271374
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    279382        CheckParameterUtil.ensureParameterNotNull(parameters, "parameters");
    280383        if (parameters.equals(OAuthParameters.createDefault(apiUrl, parameters.getOAuthVersion()))) {
    281384            cbUseDefaults.setSelected(true);
    282             setChildComponentsEnabled(false);
     385            setChildComponentsVisible(false);
    283386        } else {
    284387            cbUseDefaults.setSelected(false);
    285             setChildComponentsEnabled(true);
     388            setChildComponentsVisible(true);
    286389            if (parameters instanceof OAuth20Parameters) {
    287390                OAuth20Parameters parameters20 = (OAuth20Parameters) parameters;
    288                 tfConsumerKey.setText(parameters20.getClientId());
    289                 tfConsumerSecret.setText(parameters20.getClientSecret());
     391                tfClientId.setText(parameters20.getClientId());
     392                tfClientSecret.setText(parameters20.getClientSecret());
    290393                tfAccessTokenURL.setText(parameters20.getAccessTokenUrl());
    291394                tfAuthoriseURL.setText(parameters20.getAuthorizationUrl());
    292                 tfRequestTokenURL.setText(parameters20.getRedirectUri());
     395                tfRedirectUri.setText(parameters20.getRedirectUri());
    293396            }
    294397        }
    295398    }
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    302405     */
    303406    public void initialize(String paramApiUrl) {
    304407        CheckParameterUtil.ensureParameterNotNull(paramApiUrl, "paramApiUrl");
    305         setApiUrl(paramApiUrl);
    306         boolean useDefault = Config.getPref().getBoolean("oauth.settings.use-default", true);
     408        this.apiUrl = paramApiUrl;
     409        // "use default settings" is a setting of each server
     410        boolean useDefault = OAuthParameters.isUseDefault(paramApiUrl);
    307411        ilUseDefault.setEnabled(false);
     412        cbUseDefaults.setSelected(useDefault);
     413        setChildComponentsVisible(!useDefault);
    308414        MainApplication.worker.execute(() -> {
    309415            if (useDefault) {
    310416                this.resetToDefaultSettings();
    311417            } else {
    312418                // createFromApiUrl may make a network request
    313                 final IOAuthParameters parameters = OAuthParameters.createFromApiUrl(paramApiUrl, OAuthVersion.OAuth20);
     419                final IOAuthParameters parameters = OAuthParameters.createFromApiUrl(paramApiUrl, this.oauthVersion);
    314420                GuiHelper.runInEDT(() -> setAdvancedParameters(parameters));
    315421            }
    316422            GuiHelper.runInEDT(() -> ilUseDefault.setEnabled(true));
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    318424    }
    319425
    320426    /**
    321      * Remembers the current values in the preferences <code>pref</code>.
     427     * Remembers the current values in the preferences <code>pref</code>: whether the server uses the default
     428     * settings, and the settings entered if not. Settings entered earlier are kept when the default settings are
     429     * used, so that they are there again when they are needed again.
    322430     */
    323431    public void rememberPreferences() {
    324         Config.getPref().putBoolean("oauth.settings.use-default", cbUseDefaults.isSelected());
    325         if (cbUseDefaults.isSelected()) {
    326             MainApplication.worker.execute(() -> OAuthParameters.createDefault().rememberPreferences());
    327         } else {
     432        if (apiUrl == null) {
     433            return; // not initialized
     434        }
     435        OAuthParameters.setUseDefault(apiUrl, cbUseDefaults.isSelected());
     436        if (!cbUseDefaults.isSelected()) {
    328437            getAdvancedParameters().rememberPreferences();
    329438        }
    330439    }
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    344453                MainApplication.worker.execute(AdvancedOAuthPropertiesPanel.this::resetToDefaultSettings);
    345454                break;
    346455            case ItemEvent.DESELECTED:
    347                 setChildComponentsEnabled(true);
     456                setChildComponentsVisible(true);
    348457                break;
    349458            default: // Do nothing
    350459            }
    … … public class AdvancedOAuthPropertiesPanel extends VerticallyScrollablePanel {  
    362471     * @since 5422
    363472     */
    364473    public void setApiUrl(String apiUrl) {
     474        if (this.apiUrl != null && apiUrl != null
     475                && !Objects.equals(OAuthParameters.getHost(this.apiUrl), OAuthParameters.getHost(apiUrl))) {
     476            // another server, with settings of its own
     477            initialize(apiUrl);
     478            return;
     479        }
    365480        this.apiUrl = apiUrl;
    366481        if (cbUseDefaults.isSelected()) {
    367482            MainApplication.worker.execute(this::resetToDefaultSettings);
  • deleted file src/org/openstreetmap/josm/gui/oauth/AuthorizationProcedure.java

    diff --git src/org/openstreetmap/josm/gui/oauth/AuthorizationProcedure.java src/org/openstreetmap/josm/gui/oauth/AuthorizationProcedure.java
    deleted file mode 100644
    index a8fa2a4afa..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 /**
    7  * The type of procedure to use for retrieving OAuth credentials.
    8  */
    9 public enum AuthorizationProcedure {
    10     /**
    11      * Run a fully automatic procedure to get an access token from the OSM website.
    12      * JOSM accesses the OSM website on behalf of the JOSM user and interacts
    13      * with the site using an OSM session, form posting and screen scraping.
    14      */
    15     FULLY_AUTOMATIC,
    16 
    17     /**
    18      * Run a semi-automatic procedure to get an access token from the OSM website.
    19      * JOSM submits the standards OAuth requests to get a Request Token and an
    20      * Access Token. It dispatches the user to the OSM website in an external browser
    21      * to authenticate itself and to accept the request token submitted by JOSM.
    22      */
    23     SEMI_AUTOMATIC,
    24 
    25     /**
    26      * Enter an Access Token manually. The Access Token could have been generated
    27      * by another JOSM user and sent to the current JOSM user via email, i.e. in order
    28      * to grant the current OSM user the right download its private GPS traces. Or it could
    29      * have been generated in a former session and filed away in a secure place.
    30      */
    31     MANUALLY;
    32 
    33     /**
    34      * Returns the translated name of this procedure
    35      * @return the translated name of this procedure
    36      */
    37     public String getText() {
    38         switch (this) {
    39         case FULLY_AUTOMATIC:
    40             return tr("Fully automatic");
    41         case SEMI_AUTOMATIC:
    42             return tr("Semi-automatic");
    43         case MANUALLY:
    44             return tr("Manual");
    45         }
    46         throw new IllegalStateException();
    47     }
    48 
    49     /**
    50      * Returns a translated description of this procedure
    51      * @return a translated description of this procedure
    52      */
    53     public String getDescription() {
    54         switch (this) {
    55         case FULLY_AUTOMATIC:
    56             return tr(
    57                     "<html>Run a fully automatic procedure to get an access token from the OSM website.<br>"
    58                     + "JOSM accesses the OSM website on behalf of the JOSM user and fully<br>"
    59                     + "automatically authorizes the user and retrieves an Access Token.</html>"
    60             );
    61         case SEMI_AUTOMATIC:
    62             return tr(
    63                     "<html>Run a semi-automatic procedure to get an access token from the OSM website.<br>"
    64                     + "JOSM submits the standards OAuth requests to get a Request Token and an<br>"
    65                     + "Access Token. It dispatches the user to the OSM website in an external browser<br>"
    66                     + "to authenticate itself and to accept the request token submitted by JOSM.</html>"
    67             );
    68         case MANUALLY:
    69             return tr(
    70                     "<html>Enter an Access Token manually if it was generated and retrieved outside<br>"
    71                     + "of JOSM.</html>"
    72             );
    73         }
    74         throw new IllegalStateException();
    75     }
    76 }
  • deleted file src/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUI.java

    diff --git src/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUI.java src/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUI.java
    deleted file mode 100644
    index 310019e450..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 import java.awt.BorderLayout;
    7 import java.awt.Component;
    8 import java.awt.FlowLayout;
    9 import java.awt.Font;
    10 import java.awt.GridBagConstraints;
    11 import java.awt.GridBagLayout;
    12 import java.awt.Insets;
    13 import java.awt.event.ActionEvent;
    14 import java.io.IOException;
    15 import java.util.concurrent.Executor;
    16 
    17 import javax.swing.AbstractAction;
    18 import javax.swing.BorderFactory;
    19 import javax.swing.JButton;
    20 import javax.swing.JLabel;
    21 import javax.swing.JOptionPane;
    22 import javax.swing.JPanel;
    23 import javax.swing.JTabbedPane;
    24 import javax.swing.text.html.HTMLEditorKit;
    25 
    26 import org.openstreetmap.josm.data.oauth.IOAuthToken;
    27 import org.openstreetmap.josm.data.oauth.OAuthVersion;
    28 import org.openstreetmap.josm.gui.HelpAwareOptionPane;
    29 import org.openstreetmap.josm.gui.PleaseWaitRunnable;
    30 import org.openstreetmap.josm.gui.help.HelpUtil;
    31 import org.openstreetmap.josm.gui.util.GuiHelper;
    32 import org.openstreetmap.josm.gui.widgets.HtmlPanel;
    33 import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
    34 import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
    35 import org.openstreetmap.josm.io.OsmTransferException;
    36 import org.openstreetmap.josm.tools.ImageProvider;
    37 import org.openstreetmap.josm.tools.Logging;
    38 import org.xml.sax.SAXException;
    39 
    40 /**
    41  * This is a UI which supports a JOSM user to get an OAuth Access Token in a fully
    42  * automatic process.
    43  *
    44  * @since 2746
    45  */
    46 public class FullyAutomaticAuthorizationUI extends AbstractAuthorizationUI {
    47     private final AccessTokenInfoPanel pnlAccessTokenInfo = new AccessTokenInfoPanel();
    48     private OsmPrivilegesPanel pnlOsmPrivileges;
    49     private JPanel pnlPropertiesPanel;
    50     private JPanel pnlActionButtonsPanel;
    51     private JPanel pnlResult;
    52     private final transient Executor executor;
    53 
    54     /**
    55      * Builds the panel with the three privileges the user can grant JOSM
    56      *
    57      * @return constructed panel for the privileges
    58      */
    59     protected VerticallyScrollablePanel buildGrantsPanel() {
    60         pnlOsmPrivileges = new OsmPrivilegesPanel();
    61         return pnlOsmPrivileges;
    62     }
    63 
    64     /**
    65      * Builds the panel for entering the username and password
    66      *
    67      * @return constructed panel for the credentials
    68      */
    69     protected VerticallyScrollablePanel buildUserNamePasswordPanel() {
    70         VerticallyScrollablePanel pnl = new VerticallyScrollablePanel(new GridBagLayout());
    71         GridBagConstraints gc = new GridBagConstraints();
    72         pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    73 
    74         gc.anchor = GridBagConstraints.NORTHWEST;
    75         gc.fill = GridBagConstraints.HORIZONTAL;
    76         gc.weightx = 1.0;
    77         gc.gridwidth = 2;
    78         HtmlPanel pnlMessage = new HtmlPanel();
    79         HTMLEditorKit kit = (HTMLEditorKit) pnlMessage.getEditorPane().getEditorKit();
    80         kit.getStyleSheet().addRule(
    81                 ".warning-body {background-color:#DDFFDD; padding: 10pt; " +
    82                 "border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}");
    83         kit.getStyleSheet().addRule("ol {margin-left: 1cm}");
    84         pnlMessage.setText("<html><body><p class=\"warning-body\">"
    85                 + tr("Please enter your OSM user name and password. The password will <strong>not</strong> be saved "
    86                         + "in clear text in the JOSM preferences and it will be submitted to the OSM server <strong>only once</strong>. "
    87                         + "Subsequent data upload requests don''t use your password any more.").replace(". ", ".<br>")
    88                         + "</p>"
    89                         + "</body></html>");
    90         pnl.add(pnlMessage, gc);
    91 
    92         // the user name input field
    93         gc.gridy = 1;
    94         gc.gridwidth = 1;
    95         gc.anchor = GridBagConstraints.NORTHWEST;
    96         gc.fill = GridBagConstraints.HORIZONTAL;
    97         gc.weightx = 0.0;
    98         gc.insets = new Insets(0, 0, 3, 3);
    99         pnl.add(new JLabel(tr("Username: ")), gc);
    100 
    101         // the password input field
    102         gc.anchor = GridBagConstraints.NORTHWEST;
    103         gc.fill = GridBagConstraints.HORIZONTAL;
    104         gc.gridy = 2;
    105         gc.gridx = 0;
    106         gc.weightx = 0.0;
    107         pnl.add(new JLabel(tr("Password:")), gc);
    108 
    109         // filler - grab remaining space
    110         gc.gridx = 1;
    111         gc.gridy = 4;
    112         gc.gridwidth = 2;
    113         gc.fill = GridBagConstraints.BOTH;
    114         gc.weightx = 1.0;
    115         gc.weighty = 1.0;
    116         pnl.add(new JPanel(), gc);
    117 
    118         return pnl;
    119     }
    120 
    121     protected JPanel buildPropertiesPanel() {
    122         JPanel pnl = new JPanel(new BorderLayout());
    123 
    124         JTabbedPane tpProperties = new JTabbedPane();
    125         tpProperties.add(buildUserNamePasswordPanel().getVerticalScrollPane());
    126         tpProperties.add(buildGrantsPanel().getVerticalScrollPane());
    127         tpProperties.add(getAdvancedPropertiesPanel().getVerticalScrollPane());
    128         tpProperties.setTitleAt(0, tr("Basic"));
    129         tpProperties.setTitleAt(1, tr("Granted rights"));
    130         tpProperties.setTitleAt(2, tr("Advanced OAuth properties"));
    131 
    132         pnl.add(tpProperties, BorderLayout.CENTER);
    133         return pnl;
    134     }
    135 
    136     /**
    137      * Builds the panel with the action button  for starting the authorisation
    138      *
    139      * @return constructed button panel
    140      */
    141     protected JPanel buildActionButtonPanel() {
    142         JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
    143 
    144         RunAuthorisationAction runAuthorisationAction = new RunAuthorisationAction();
    145         pnl.add(new JButton(runAuthorisationAction));
    146         return pnl;
    147     }
    148 
    149     /**
    150      * Builds the panel which displays the generated Access Token.
    151      *
    152      * @return constructed panel for the results
    153      */
    154     protected JPanel buildResultsPanel() {
    155         JPanel pnl = new JPanel(new GridBagLayout());
    156         GridBagConstraints gc = new GridBagConstraints();
    157         pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    158 
    159         // the message panel
    160         gc.anchor = GridBagConstraints.NORTHWEST;
    161         gc.fill = GridBagConstraints.HORIZONTAL;
    162         gc.weightx = 1.0;
    163         JMultilineLabel msg = new JMultilineLabel("");
    164         msg.setFont(msg.getFont().deriveFont(Font.PLAIN));
    165         String lbl = tr("Accept Access Token");
    166         msg.setText(tr("<html>"
    167                 + "You have successfully retrieved an OAuth Access Token from the OSM website. "
    168                 + "Click on <strong>{0}</strong> to accept the token. JOSM will use it in "
    169                 + "subsequent requests to gain access to the OSM API."
    170                 + "</html>", lbl));
    171         pnl.add(msg, gc);
    172 
    173         // infos about the access token
    174         gc.gridy = 1;
    175         gc.insets = new Insets(5, 0, 0, 0);
    176         pnl.add(pnlAccessTokenInfo, gc);
    177 
    178         // the actions
    179         JPanel pnl1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
    180         pnl1.add(new JButton(new BackAction()));
    181         pnl1.add(new JButton(new TestAccessTokenAction()));
    182         gc.gridy = 2;
    183         pnl.add(pnl1, gc);
    184 
    185         // filler - grab the remaining space
    186         gc.gridy = 3;
    187         gc.fill = GridBagConstraints.BOTH;
    188         gc.weightx = 1.0;
    189         gc.weighty = 1.0;
    190         pnl.add(new JPanel(), gc);
    191 
    192         return pnl;
    193     }
    194 
    195     protected final void build() {
    196         setLayout(new BorderLayout());
    197         pnlPropertiesPanel = buildPropertiesPanel();
    198         pnlActionButtonsPanel = buildActionButtonPanel();
    199         pnlResult = buildResultsPanel();
    200 
    201         prepareUIForEnteringRequest();
    202     }
    203 
    204     /**
    205      * Prepares the UI for the first step in the automatic process: entering the authentication
    206      * and authorisation parameters.
    207      *
    208      */
    209     protected void prepareUIForEnteringRequest() {
    210         removeAll();
    211         add(pnlPropertiesPanel, BorderLayout.CENTER);
    212         add(pnlActionButtonsPanel, BorderLayout.SOUTH);
    213         pnlPropertiesPanel.revalidate();
    214         pnlActionButtonsPanel.revalidate();
    215         validate();
    216         repaint();
    217 
    218         setAccessToken(null);
    219     }
    220 
    221     /**
    222      * Prepares the UI for the second step in the automatic process: displaying the access token
    223      *
    224      */
    225     protected void prepareUIForResultDisplay() {
    226         removeAll();
    227         add(pnlResult, BorderLayout.CENTER);
    228         validate();
    229         repaint();
    230     }
    231 
    232     /**
    233      * Constructs a new {@code FullyAutomaticAuthorizationUI} for the given API URL.
    234      * @param apiUrl The OSM API URL
    235      * @param executor the executor used for running the HTTP requests for the authorization
    236      * @param oAuthVersion The OAuth version to use for this UI
    237      * @since 18991
    238      */
    239     public FullyAutomaticAuthorizationUI(String apiUrl, Executor executor, OAuthVersion oAuthVersion) {
    240         super(apiUrl, oAuthVersion);
    241         this.executor = executor;
    242         build();
    243     }
    244 
    245     @Override
    246     public boolean isSaveAccessTokenToPreferences() {
    247         return pnlAccessTokenInfo.isSaveToPreferences();
    248     }
    249 
    250     @Override
    251     protected void setAccessToken(IOAuthToken accessToken) {
    252         super.setAccessToken(accessToken);
    253         pnlAccessTokenInfo.setAccessToken(accessToken);
    254     }
    255 
    256     /**
    257      * Starts the authorisation process
    258      */
    259     class RunAuthorisationAction extends AbstractAction {
    260         RunAuthorisationAction() {
    261             putValue(NAME, tr("Authorize now"));
    262             new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
    263             putValue(SHORT_DESCRIPTION, tr("Click to redirect you to the authorization form on the JOSM web site"));
    264         }
    265 
    266         @Override
    267         public void actionPerformed(ActionEvent evt) {
    268             executor.execute(new FullyAutomaticAuthorisationTask(FullyAutomaticAuthorizationUI.this));
    269         }
    270     }
    271 
    272     /**
    273      * Action to go back to step 1 in the process
    274      */
    275     class BackAction extends AbstractAction {
    276         BackAction() {
    277             putValue(NAME, tr("Back"));
    278             putValue(SHORT_DESCRIPTION, tr("Run the automatic authorization steps again"));
    279             new ImageProvider("dialogs", "previous").getResource().attachImageIcon(this);
    280         }
    281 
    282         @Override
    283         public void actionPerformed(ActionEvent arg0) {
    284             prepareUIForEnteringRequest();
    285         }
    286     }
    287 
    288     /**
    289      * Action to test an access token.
    290      */
    291     class TestAccessTokenAction extends AbstractAction {
    292         TestAccessTokenAction() {
    293             putValue(NAME, tr("Test Access Token"));
    294             new ImageProvider("logo").getResource().attachImageIcon(this);
    295         }
    296 
    297         @Override
    298         public void actionPerformed(ActionEvent arg0) {
    299             executor.execute(new TestAccessTokenTask(
    300                     FullyAutomaticAuthorizationUI.this,
    301                     getApiUrl(),
    302                     getAccessToken()
    303             ));
    304         }
    305     }
    306 
    307     class FullyAutomaticAuthorisationTask extends PleaseWaitRunnable {
    308         private boolean canceled;
    309 
    310         FullyAutomaticAuthorisationTask(Component parent) {
    311             super(parent, tr("Authorize JOSM to access the OSM API"), false /* don't ignore exceptions */);
    312         }
    313 
    314         @Override
    315         protected void cancel() {
    316             canceled = true;
    317         }
    318 
    319         @Override
    320         protected void finish() {
    321             // Do nothing
    322         }
    323 
    324         protected void alertAuthorisationFailed() {
    325             HelpAwareOptionPane.showOptionDialog(
    326                     FullyAutomaticAuthorizationUI.this,
    327                     tr("<html>"
    328                             + "The automatic process for retrieving an OAuth Access Token<br>"
    329                             + "from the OSM server failed.<br><br>"
    330                             + "Please try again or choose another kind of authorization process,<br>"
    331                             + "i.e. semi-automatic or manual authorization."
    332                             +"</html>"),
    333                     tr("OAuth authorization failed"),
    334                     JOptionPane.ERROR_MESSAGE,
    335                     HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
    336             );
    337         }
    338 
    339         protected void alertInvalidLoginUrl() {
    340             HelpAwareOptionPane.showOptionDialog(
    341                     FullyAutomaticAuthorizationUI.this,
    342                     tr("<html>"
    343                             + "The automatic process for retrieving an OAuth Access Token<br>"
    344                             + "from the OSM server failed because JOSM was not able to build<br>"
    345                             + "a valid login URL from the OAuth Authorize Endpoint URL ''{0}''.<br><br>"
    346                             + "Please check your advanced setting and try again."
    347                             + "</html>",
    348                             getAdvancedPropertiesPanel().getAdvancedParameters().getAuthorizationUrl()),
    349                     tr("OAuth authorization failed"),
    350                     JOptionPane.ERROR_MESSAGE,
    351                     HelpUtil.ht("/Dialog/OAuthAuthorisationWizard#FullyAutomaticProcessFailed")
    352             );
    353         }
    354 
    355         protected void handleException(final OsmOAuthAuthorizationException e) {
    356             Logging.error(e);
    357             GuiHelper.runInEDT(this::alertAuthorisationFailed);
    358         }
    359 
    360         @Override
    361         protected void realRun() throws SAXException, IOException, OsmTransferException {
    362             getProgressMonitor().setTicksCount(2);
    363             OAuthAuthorizationWizard.authorize(true, token -> {
    364                 if (!canceled) {
    365                     getProgressMonitor().worked(1);
    366                     GuiHelper.runInEDT(() -> {
    367                         prepareUIForResultDisplay();
    368                         setAccessToken(token.orElse(null));
    369                     });
    370                 }
    371             }, getApiUrl(), getOAuthVersion(), getOAuthParameters());
    372             getProgressMonitor().worked(1);
    373         }
    374     }
    375 }
  • deleted file src/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanel.java

    diff --git src/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanel.java src/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanel.java
    deleted file mode 100644
    index eaa228b1b5..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 import java.awt.GridBagConstraints;
    7 import java.awt.GridBagLayout;
    8 import java.awt.Insets;
    9 
    10 import javax.swing.BorderFactory;
    11 import javax.swing.JLabel;
    12 import javax.swing.JPanel;
    13 
    14 import org.openstreetmap.josm.gui.preferences.server.UserNameValidator;
    15 import org.openstreetmap.josm.gui.widgets.JosmPasswordField;
    16 import org.openstreetmap.josm.gui.widgets.JosmTextField;
    17 import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
    18 
    19 /**
    20  * Panel to enter username and password for the "fully automatic" authorization
    21  * procedure.
    22  *
    23  * @see AuthorizationProcedure#FULLY_AUTOMATIC
    24  */
    25 public class FullyAutomaticPropertiesPanel extends JPanel {
    26 
    27     private final JosmTextField tfUserName = new JosmTextField();
    28     private final JosmPasswordField tfPassword = new JosmPasswordField();
    29 
    30     /**
    31      * Constructs a new {@code FullyAutomaticPropertiesPanel}.
    32      */
    33     public FullyAutomaticPropertiesPanel() {
    34         setLayout(new GridBagLayout());
    35         GridBagConstraints gc = new GridBagConstraints();
    36         setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
    37 
    38         gc.anchor = GridBagConstraints.NORTHWEST;
    39         gc.fill = GridBagConstraints.HORIZONTAL;
    40         gc.weightx = 1.0;
    41         add(buildUserNamePasswordPanel(), gc);
    42 
    43         gc.gridy = 1;
    44         gc.weighty = 1.0;
    45         gc.fill = GridBagConstraints.BOTH;
    46         add(new JPanel(), gc);
    47     }
    48 
    49     protected final JPanel buildUserNamePasswordPanel() {
    50         JPanel pnl = new JPanel(new GridBagLayout());
    51         GridBagConstraints gc = new GridBagConstraints();
    52 
    53         gc.anchor = GridBagConstraints.NORTHWEST;
    54         gc.fill = GridBagConstraints.HORIZONTAL;
    55         gc.weightx = 0.0;
    56         gc.insets = new Insets(0, 0, 3, 3);
    57         pnl.add(new JLabel(tr("Username: ")), gc);
    58 
    59         gc.gridx = 1;
    60         gc.weightx = 1.0;
    61         pnl.add(tfUserName, gc);
    62         SelectAllOnFocusGainedDecorator.decorate(tfUserName);
    63         UserNameValidator valUserName = new UserNameValidator(tfUserName);
    64         valUserName.validate();
    65 
    66         gc.anchor = GridBagConstraints.NORTHWEST;
    67         gc.fill = GridBagConstraints.HORIZONTAL;
    68         gc.gridy = 1;
    69         gc.gridx = 0;
    70         gc.weightx = 0.0;
    71         pnl.add(new JLabel(tr("Password:")), gc);
    72 
    73         gc.gridx = 1;
    74         gc.weightx = 1.0;
    75         pnl.add(tfPassword, gc);
    76         SelectAllOnFocusGainedDecorator.decorate(tfPassword);
    77 
    78         return pnl;
    79     }
    80 }
  • deleted file src/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUI.java

    diff --git src/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUI.java src/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUI.java
    deleted file mode 100644
    index 3a393f4f11..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 import java.awt.BorderLayout;
    7 import java.awt.FlowLayout;
    8 import java.awt.GridBagConstraints;
    9 import java.awt.GridBagLayout;
    10 import java.awt.Insets;
    11 import java.awt.event.ActionEvent;
    12 import java.beans.PropertyChangeEvent;
    13 import java.beans.PropertyChangeListener;
    14 import java.util.concurrent.Executor;
    15 
    16 import javax.swing.AbstractAction;
    17 import javax.swing.BorderFactory;
    18 import javax.swing.JButton;
    19 import javax.swing.JCheckBox;
    20 import javax.swing.JLabel;
    21 import javax.swing.JPanel;
    22 import javax.swing.JTabbedPane;
    23 import javax.swing.event.DocumentEvent;
    24 import javax.swing.event.DocumentListener;
    25 import javax.swing.text.JTextComponent;
    26 
    27 import org.openstreetmap.josm.data.oauth.OAuth20Exception;
    28 import org.openstreetmap.josm.data.oauth.OAuth20Token;
    29 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    30 import org.openstreetmap.josm.data.oauth.OAuthVersion;
    31 import org.openstreetmap.josm.gui.widgets.DefaultTextComponentValidator;
    32 import org.openstreetmap.josm.gui.widgets.HtmlPanel;
    33 import org.openstreetmap.josm.gui.widgets.JosmTextField;
    34 import org.openstreetmap.josm.gui.widgets.SelectAllOnFocusGainedDecorator;
    35 import org.openstreetmap.josm.tools.ImageProvider;
    36 import org.openstreetmap.josm.tools.JosmRuntimeException;
    37 
    38 /**
    39  * This is an UI which supports a JOSM user to get an OAuth Access Token in a fully manual process.
    40  *
    41  * @since 2746
    42  */
    43 public class ManualAuthorizationUI extends AbstractAuthorizationUI {
    44 
    45     private final JosmTextField tfAccessTokenKey = new JosmTextField();
    46     private transient AccessTokenKeyValidator valAccessTokenKey;
    47     private final JCheckBox cbSaveToPreferences = new JCheckBox(tr("Save Access Token in preferences"));
    48     private final HtmlPanel pnlMessage = new HtmlPanel();
    49     private final transient Executor executor;
    50 
    51     /**
    52      * Constructs a new {@code ManualAuthorizationUI} for the given API URL.
    53      * @param apiUrl The OSM API URL
    54      * @param executor the executor used for running the HTTP requests for the authorization
    55      * @param oAuthVersion The OAuthVersion to use for this UI
    56      * @since 18991
    57      */
    58     public ManualAuthorizationUI(String apiUrl, Executor executor, OAuthVersion oAuthVersion) {
    59         super(null /* don't pass apiURL because setApiUrl is overridden and references a local field */,
    60                 oAuthVersion);
    61         setApiUrl(apiUrl);
    62         this.executor = executor;
    63         build();
    64     }
    65 
    66     protected JPanel buildAccessTokenPanel() {
    67         JPanel pnl = new JPanel(new GridBagLayout());
    68         pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    69         GridBagConstraints gc = new GridBagConstraints();
    70         AccessTokenBuilder accessTokenBuilder = new AccessTokenBuilder();
    71 
    72         // the access token key input field
    73         gc.anchor = GridBagConstraints.NORTHWEST;
    74         gc.fill = GridBagConstraints.HORIZONTAL;
    75         gc.weightx = 0.0;
    76         gc.gridwidth = 2;
    77         gc.insets = new Insets(0, 0, 5, 0);
    78         pnlMessage.setText("<html><body>"
    79                 + tr("Please enter an OAuth Access Token which is authorized to access the OSM server "
    80                         + "''{0}''.",
    81                         getApiUrl()) + "</body></html>");
    82         pnl.add(pnlMessage, gc);
    83 
    84         // the access token key input field
    85         gc.gridy = 1;
    86         gc.weightx = 0.0;
    87         gc.gridwidth = 1;
    88         gc.insets = new Insets(0, 0, 0, 3);
    89         pnl.add(new JLabel(tr("Access Token Key:")), gc);
    90 
    91         gc.gridx = 1;
    92         gc.weightx = 1.0;
    93         pnl.add(tfAccessTokenKey, gc);
    94         SelectAllOnFocusGainedDecorator.decorate(tfAccessTokenKey);
    95         valAccessTokenKey = new AccessTokenKeyValidator(tfAccessTokenKey);
    96         valAccessTokenKey.validate();
    97         tfAccessTokenKey.getDocument().addDocumentListener(accessTokenBuilder);
    98 
    99         // the checkbox for saving to preferences
    100         gc.gridy = 3;
    101         gc.gridx = 0;
    102         gc.gridwidth = 2;
    103         gc.weightx = 1.0;
    104         pnl.add(cbSaveToPreferences, gc);
    105         cbSaveToPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences());
    106 
    107         // filler - grab remaining space
    108         gc.gridy = 3;
    109         gc.gridx = 0;
    110         gc.gridwidth = 2;
    111         gc.weightx = 1.0;
    112         gc.weighty = 1.0;
    113         gc.fill = GridBagConstraints.BOTH;
    114         pnl.add(new JPanel(), gc);
    115         return pnl;
    116     }
    117 
    118     protected JPanel buildTabbedPreferencesPanel() {
    119         JPanel pnl = new JPanel(new BorderLayout());
    120 
    121         JTabbedPane tp = new JTabbedPane();
    122         tp.add(buildAccessTokenPanel());
    123         tp.add(getAdvancedPropertiesPanel());
    124 
    125         tp.setTitleAt(0, tr("Access Token"));
    126         tp.setTitleAt(1, tr("Advanced OAuth parameters"));
    127 
    128         tp.setToolTipTextAt(0, tr("Enter the OAuth Access Token"));
    129         tp.setToolTipTextAt(1, tr("Enter advanced OAuth properties"));
    130 
    131         pnl.add(tp, BorderLayout.CENTER);
    132         return pnl;
    133     }
    134 
    135     protected JPanel buildActionsPanel() {
    136         JPanel pnl = new JPanel(new FlowLayout(FlowLayout.LEFT));
    137         TestAccessTokenAction actTestAccessToken = new TestAccessTokenAction();
    138         pnl.add(new JButton(actTestAccessToken));
    139         this.addPropertyChangeListener(actTestAccessToken);
    140         return pnl;
    141     }
    142 
    143     @Override
    144     public void setApiUrl(String apiUrl) {
    145         super.setApiUrl(apiUrl);
    146         if (pnlMessage != null) {
    147             pnlMessage.setText(tr("<html><body>"
    148                     + "Please enter an OAuth Access Token which is authorized to access the OSM server "
    149                     + "''{0}''."
    150                     + "</body></html>",
    151                     getApiUrl()
    152             ));
    153         }
    154     }
    155 
    156     protected final void build() {
    157         setLayout(new BorderLayout());
    158         setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    159         add(buildTabbedPreferencesPanel(), BorderLayout.CENTER);
    160         add(buildActionsPanel(), BorderLayout.SOUTH);
    161     }
    162 
    163     @Override
    164     public boolean isSaveAccessTokenToPreferences() {
    165         return cbSaveToPreferences.isSelected();
    166     }
    167 
    168     private static class AccessTokenKeyValidator extends DefaultTextComponentValidator {
    169         AccessTokenKeyValidator(JTextComponent tc) {
    170             super(tc, tr("Please enter an Access Token Key"),
    171                       tr("The Access Token Key must not be empty. Please enter an Access Token Key"));
    172         }
    173     }
    174 
    175     class AccessTokenBuilder implements DocumentListener {
    176 
    177         public void build() {
    178             if (!valAccessTokenKey.isValid()) {
    179                 setAccessToken(null);
    180             } else {
    181                 try {
    182                     setAccessToken(new OAuth20Token(getOAuthParameters(), "{\"token_type\":\"bearer\", \"access_token\":\""
    183                             + tfAccessTokenKey.getText().trim() + "\"}"));
    184                 } catch (OAuth20Exception e) {
    185                     throw new JosmRuntimeException(e);
    186                 }
    187             }
    188         }
    189 
    190         @Override
    191         public void changedUpdate(DocumentEvent e) {
    192             build();
    193         }
    194 
    195         @Override
    196         public void insertUpdate(DocumentEvent e) {
    197             build();
    198         }
    199 
    200         @Override
    201         public void removeUpdate(DocumentEvent e) {
    202             build();
    203         }
    204     }
    205 
    206     /**
    207      * Action for testing an Access Token
    208      */
    209     class TestAccessTokenAction extends AbstractAction implements PropertyChangeListener {
    210         TestAccessTokenAction() {
    211             putValue(NAME, tr("Test Access Token"));
    212             new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
    213             putValue(SHORT_DESCRIPTION, tr("Click to test the Access Token"));
    214             updateEnabledState();
    215         }
    216 
    217         @Override
    218         public void actionPerformed(ActionEvent evt) {
    219             TestAccessTokenTask task = new TestAccessTokenTask(
    220                     ManualAuthorizationUI.this,
    221                     getApiUrl(),
    222                     getAccessToken()
    223             );
    224             executor.execute(task);
    225         }
    226 
    227         protected final void updateEnabledState() {
    228             setEnabled(hasAccessToken());
    229         }
    230 
    231         @Override
    232         public void propertyChange(PropertyChangeEvent evt) {
    233             if (!evt.getPropertyName().equals(AbstractAuthorizationUI.ACCESS_TOKEN_PROP))
    234                 return;
    235             updateEnabledState();
    236         }
    237     }
    238 }
  • deleted file src/org/openstreetmap/josm/gui/oauth/OAuthAuthorizationWizard.java

    diff --git src/org/openstreetmap/josm/gui/oauth/OAuthAuthorizationWizard.java src/org/openstreetmap/josm/gui/oauth/OAuthAuthorizationWizard.java
    deleted file mode 100644
    index a4ff52d723..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 import java.awt.BorderLayout;
    7 import java.awt.Component;
    8 import java.awt.Dimension;
    9 import java.awt.FlowLayout;
    10 import java.awt.Font;
    11 import java.awt.GridBagConstraints;
    12 import java.awt.GridBagLayout;
    13 import java.awt.event.ActionEvent;
    14 import java.awt.event.ComponentAdapter;
    15 import java.awt.event.ComponentEvent;
    16 import java.awt.event.WindowAdapter;
    17 import java.awt.event.WindowEvent;
    18 import java.beans.PropertyChangeEvent;
    19 import java.beans.PropertyChangeListener;
    20 import java.lang.reflect.InvocationTargetException;
    21 import java.net.URL;
    22 import java.util.Objects;
    23 import java.util.Optional;
    24 import java.util.concurrent.Executor;
    25 import java.util.concurrent.FutureTask;
    26 import java.util.function.Consumer;
    27 
    28 import javax.swing.AbstractAction;
    29 import javax.swing.BorderFactory;
    30 import javax.swing.JButton;
    31 import javax.swing.JDialog;
    32 import javax.swing.JOptionPane;
    33 import javax.swing.JPanel;
    34 import javax.swing.JScrollPane;
    35 import javax.swing.SwingUtilities;
    36 import javax.swing.UIManager;
    37 import javax.swing.text.html.HTMLEditorKit;
    38 
    39 import org.openstreetmap.josm.data.oauth.IOAuthParameters;
    40 import org.openstreetmap.josm.data.oauth.IOAuthToken;
    41 import org.openstreetmap.josm.data.oauth.OAuth20Authorization;
    42 import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    43 import org.openstreetmap.josm.data.oauth.OAuthParameters;
    44 import org.openstreetmap.josm.data.oauth.OAuthVersion;
    45 import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
    46 import org.openstreetmap.josm.gui.MainApplication;
    47 import org.openstreetmap.josm.gui.help.ContextSensitiveHelpAction;
    48 import org.openstreetmap.josm.gui.help.HelpUtil;
    49 import org.openstreetmap.josm.gui.util.GuiHelper;
    50 import org.openstreetmap.josm.gui.util.WindowGeometry;
    51 import org.openstreetmap.josm.gui.widgets.HtmlPanel;
    52 import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
    53 import org.openstreetmap.josm.io.auth.CredentialsManager;
    54 import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
    55 import org.openstreetmap.josm.spi.preferences.Config;
    56 import org.openstreetmap.josm.tools.GBC;
    57 import org.openstreetmap.josm.tools.ImageProvider;
    58 import org.openstreetmap.josm.tools.InputMapUtils;
    59 import org.openstreetmap.josm.tools.UserCancelException;
    60 import org.openstreetmap.josm.tools.Utils;
    61 
    62 /**
    63  * This wizard walks the user to the necessary steps to retrieve an OAuth Access Token which
    64  * allows JOSM to access the OSM API on the users behalf.
    65  * @since 2746
    66  */
    67 public class OAuthAuthorizationWizard extends JDialog {
    68     private boolean canceled;
    69     private final AuthorizationProcedure procedure;
    70     private final String apiUrl;
    71     private final OAuthVersion oAuthVersion;
    72 
    73     private FullyAutomaticAuthorizationUI pnlFullyAutomaticAuthorisationUI;
    74     private ManualAuthorizationUI pnlManualAuthorisationUI;
    75     private JScrollPane spAuthorisationProcedureUI;
    76     private final transient Executor executor;
    77 
    78     /**
    79      * Launches the wizard, {@link OAuthAccessTokenHolder#setAccessToken(String, IOAuthToken)} sets the token
    80      * and {@link OAuthAccessTokenHolder#setSaveToPreferences(boolean) saves to preferences}.
    81      * @param callback Callback to run when authorization is finished
    82      * @throws UserCancelException if user cancels the operation
    83      */
    84     public void showDialog(Consumer<Optional<IOAuthToken>> callback) throws UserCancelException {
    85         if ((this.oAuthVersion == OAuthVersion.OAuth20 || this.oAuthVersion == OAuthVersion.OAuth21)
    86         && this.procedure == AuthorizationProcedure.FULLY_AUTOMATIC) {
    87             authorize(true, callback, this.apiUrl, this.oAuthVersion, getOAuthParameters());
    88         } else {
    89             setVisible(true);
    90             if (isCanceled()) {
    91                 throw new UserCancelException();
    92             }
    93             OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
    94             holder.setAccessToken(apiUrl, getAccessToken());
    95             holder.setSaveToPreferences(isSaveAccessTokenToPreferences());
    96         }
    97     }
    98 
    99     /**
    100      * Perform the oauth dance
    101      *
    102      * @param startRemoteControl {@code true} to start remote control if it is not already running
    103      * @param callback           The callback to use to notify that the OAuth dance succeeded
    104      * @param apiUrl             The API URL to get the token for
    105      * @param oAuthVersion       The OAuth version that the authorization dance is force
    106      * @param oAuthParameters    The OAuth parameters to use
    107      */
    108     static void authorize(boolean startRemoteControl, Consumer<Optional<IOAuthToken>> callback, String apiUrl,
    109                           OAuthVersion oAuthVersion, IOAuthParameters oAuthParameters) {
    110         final boolean remoteControlIsRunning = Boolean.TRUE.equals(RemoteControl.PROP_REMOTECONTROL_ENABLED.get());
    111         // TODO: Ask user if they want to start remote control?
    112         if (!remoteControlIsRunning && startRemoteControl) {
    113             RemoteControl.start();
    114         }
    115         new OAuth20Authorization().authorize(
    116                 Optional.ofNullable(oAuthParameters).orElseGet(() -> OAuthParameters.createDefault(apiUrl, oAuthVersion)),
    117                 token -> {
    118                     if (!remoteControlIsRunning) {
    119                         RemoteControl.stop();
    120                     }
    121                     OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, token.orElse(null));
    122                     OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
    123                     if (!token.isPresent()) {
    124                         GuiHelper.runInEDT(() -> JOptionPane.showMessageDialog(MainApplication.getMainPanel(),
    125                                 tr("Authentication failed, please check browser for details."),
    126                                 tr("OAuth Authentication Failed"),
    127                                 JOptionPane.ERROR_MESSAGE));
    128                     }
    129                     if (callback != null) {
    130                         callback.accept(token);
    131                     }
    132                 }, OsmScopes.read_gpx, OsmScopes.write_gpx,
    133                 OsmScopes.read_prefs, OsmScopes.write_prefs,
    134                 OsmScopes.write_api, OsmScopes.write_notes);
    135     }
    136 
    137     /**
    138      * Builds the row with the action buttons
    139      *
    140      * @return panel with buttons
    141      */
    142     protected JPanel buildButtonRow() {
    143         JPanel pnl = new JPanel(new FlowLayout(FlowLayout.CENTER));
    144 
    145         AcceptAccessTokenAction actAcceptAccessToken = new AcceptAccessTokenAction();
    146         pnlFullyAutomaticAuthorisationUI.addPropertyChangeListener(actAcceptAccessToken);
    147         pnlManualAuthorisationUI.addPropertyChangeListener(actAcceptAccessToken);
    148 
    149         pnl.add(new JButton(actAcceptAccessToken));
    150         pnl.add(new JButton(new CancelAction()));
    151         pnl.add(new JButton(new ContextSensitiveHelpAction(HelpUtil.ht("/Dialog/OAuthAuthorisationWizard"))));
    152 
    153         return pnl;
    154     }
    155 
    156     /**
    157      * Builds the panel with general information in the header
    158      *
    159      * @return panel with information display
    160      */
    161     protected JPanel buildHeaderInfoPanel() {
    162         JPanel pnl = new JPanel(new GridBagLayout());
    163         pnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    164 
    165         // OAuth in a nutshell ...
    166         HtmlPanel pnlMessage = new HtmlPanel();
    167         pnlMessage.setText("<html><body>"
    168                 + tr("With OAuth you grant JOSM the right to upload map data and GPS tracks "
    169                         + "on your behalf (<a href=\"{0}\">more info...</a>).", "https://wiki.openstreetmap.org/wiki/OAuth")
    170                         + "</body></html>"
    171         );
    172         pnlMessage.enableClickableHyperlinks();
    173         pnl.add(pnlMessage, GBC.eol().fill(GridBagConstraints.HORIZONTAL));
    174 
    175         // the authorisation procedure
    176         JMultilineLabel lbl = new JMultilineLabel(AuthorizationProcedure.FULLY_AUTOMATIC.getDescription());
    177         lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
    178         pnl.add(lbl, GBC.eol());
    179 
    180         if (!Config.getUrls().getDefaultOsmApiUrl().equals(apiUrl)) {
    181             final HtmlPanel pnlWarning = new HtmlPanel();
    182             final HTMLEditorKit kit = (HTMLEditorKit) pnlWarning.getEditorPane().getEditorKit();
    183             kit.getStyleSheet().addRule(".warning-body {"
    184                     + "background-color:rgb(253,255,221);padding: 10pt; "
    185                     + "border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}");
    186             kit.getStyleSheet().addRule("ol {margin-left: 1cm}");
    187             pnlWarning.setText("<html><body>"
    188                     + "<p class=\"warning-body\">"
    189                     + tr("<strong>Warning:</strong> Since you are using not the default OSM API, " +
    190                     "make sure to set an OAuth consumer key and secret in the <i>Advanced OAuth parameters</i>.")
    191                     + "</p>"
    192                     + "</body></html>");
    193             pnl.add(pnlWarning, GBC.eop().fill());
    194         }
    195 
    196         return pnl;
    197     }
    198 
    199     /**
    200      * Refreshes the view of the authorisation panel, depending on the authorisation procedure
    201      * currently selected
    202      */
    203     protected void refreshAuthorisationProcedurePanel() {
    204         switch (procedure) {
    205         case FULLY_AUTOMATIC:
    206             spAuthorisationProcedureUI.getViewport().setView(pnlFullyAutomaticAuthorisationUI);
    207             pnlFullyAutomaticAuthorisationUI.revalidate();
    208             break;
    209         case MANUALLY:
    210             spAuthorisationProcedureUI.getViewport().setView(pnlManualAuthorisationUI);
    211             pnlManualAuthorisationUI.revalidate();
    212             break;
    213         default:
    214             throw new UnsupportedOperationException("Unsupported auth type: " + procedure);
    215         }
    216         validate();
    217         repaint();
    218     }
    219 
    220     /**
    221      * builds the UI
    222      */
    223     protected final void build() {
    224         getContentPane().setLayout(new BorderLayout());
    225         getContentPane().add(buildHeaderInfoPanel(), BorderLayout.NORTH);
    226 
    227         setTitle(tr("Get an Access Token for ''{0}''", apiUrl));
    228         this.setMinimumSize(new Dimension(500, 300));
    229 
    230         pnlFullyAutomaticAuthorisationUI = new FullyAutomaticAuthorizationUI(apiUrl, executor, oAuthVersion);
    231         pnlManualAuthorisationUI = new ManualAuthorizationUI(apiUrl, executor, oAuthVersion);
    232 
    233         spAuthorisationProcedureUI = GuiHelper.embedInVerticalScrollPane(new JPanel());
    234         spAuthorisationProcedureUI.getVerticalScrollBar().addComponentListener(
    235                 new ComponentAdapter() {
    236                     @Override
    237                     public void componentShown(ComponentEvent e) {
    238                         spAuthorisationProcedureUI.setBorder(UIManager.getBorder("ScrollPane.border"));
    239                     }
    240 
    241                     @Override
    242                     public void componentHidden(ComponentEvent e) {
    243                         spAuthorisationProcedureUI.setBorder(null);
    244                     }
    245                 }
    246         );
    247         getContentPane().add(spAuthorisationProcedureUI, BorderLayout.CENTER);
    248         getContentPane().add(buildButtonRow(), BorderLayout.SOUTH);
    249 
    250         addWindowListener(new WindowEventHandler());
    251         InputMapUtils.addEscapeAction(getRootPane(), new CancelAction());
    252 
    253         refreshAuthorisationProcedurePanel();
    254 
    255         HelpUtil.setHelpContext(getRootPane(), HelpUtil.ht("/Dialog/OAuthAuthorisationWizard"));
    256     }
    257 
    258     /**
    259      * Creates the wizard.
    260      *
    261      * @param parent             the component relative to which the dialog is displayed
    262      * @param procedure          the authorization procedure to use
    263      * @param apiUrl             the API URL. Must not be null.
    264      * @param executor           the executor used for running the HTTP requests for the authorization
    265      * @param oAuthVersion       The OAuth version this wizard is for
    266      * @param advancedParameters The OAuth parameters to initialize the wizard with
    267      * @throws IllegalArgumentException if apiUrl is null
    268      */
    269     public OAuthAuthorizationWizard(Component parent, AuthorizationProcedure procedure, String apiUrl,
    270                                     Executor executor, OAuthVersion oAuthVersion, IOAuthParameters advancedParameters) {
    271         super(GuiHelper.getFrameForComponent(parent), ModalityType.DOCUMENT_MODAL);
    272         this.procedure = Objects.requireNonNull(procedure, "procedure");
    273         this.apiUrl = Objects.requireNonNull(apiUrl, "apiUrl");
    274         this.executor = executor;
    275         this.oAuthVersion = oAuthVersion;
    276         build();
    277         if (advancedParameters != null) {
    278             pnlFullyAutomaticAuthorisationUI.getAdvancedPropertiesPanel().setAdvancedParameters(advancedParameters);
    279             pnlManualAuthorisationUI.getAdvancedPropertiesPanel().setAdvancedParameters(advancedParameters);
    280         }
    281     }
    282 
    283     /**
    284      * Replies true if the dialog was canceled
    285      *
    286      * @return true if the dialog was canceled
    287      */
    288     public boolean isCanceled() {
    289         return canceled;
    290     }
    291 
    292     protected AbstractAuthorizationUI getCurrentAuthorisationUI() {
    293         switch (procedure) {
    294         case FULLY_AUTOMATIC: return pnlFullyAutomaticAuthorisationUI;
    295         case MANUALLY: return pnlManualAuthorisationUI;
    296         default: return null;
    297         }
    298     }
    299 
    300     /**
    301      * Replies the Access Token entered using the wizard
    302      *
    303      * @return the access token. May be null if the wizard was canceled.
    304      */
    305     public IOAuthToken getAccessToken() {
    306         return getCurrentAuthorisationUI().getAccessToken();
    307     }
    308 
    309     /**
    310      * Replies the current OAuth parameters.
    311      *
    312      * @return the current OAuth parameters.
    313      */
    314     public IOAuthParameters getOAuthParameters() {
    315         return getCurrentAuthorisationUI().getOAuthParameters();
    316     }
    317 
    318     /**
    319      * Replies true if the currently selected Access Token shall be saved to
    320      * the preferences.
    321      *
    322      * @return true if the currently selected Access Token shall be saved to
    323      * the preferences
    324      */
    325     public boolean isSaveAccessTokenToPreferences() {
    326         return getCurrentAuthorisationUI().isSaveAccessTokenToPreferences();
    327     }
    328 
    329     /**
    330      * Initializes the dialog with values from the preferences
    331      *
    332      */
    333     public void initFromPreferences() {
    334         pnlFullyAutomaticAuthorisationUI.initialize(apiUrl);
    335         pnlManualAuthorisationUI.initialize(apiUrl);
    336     }
    337 
    338     @Override
    339     public void setVisible(boolean visible) {
    340         if (visible) {
    341             pack();
    342             new WindowGeometry(
    343                     getClass().getName() + ".geometry",
    344                     WindowGeometry.centerInWindow(
    345                             MainApplication.getMainFrame(),
    346                             getPreferredSize()
    347                     )
    348             ).applySafe(this);
    349             initFromPreferences();
    350         } else if (isShowing()) { // Avoid IllegalComponentStateException like in #8775
    351             new WindowGeometry(this).remember(getClass().getName() + ".geometry");
    352         }
    353         super.setVisible(visible);
    354     }
    355 
    356     protected void setCanceled(boolean canceled) {
    357         this.canceled = canceled;
    358     }
    359 
    360     /**
    361      * Obtains an OAuth access token for the connection. Afterwards, the token is accessible via {@link OAuthAccessTokenHolder}.
    362      * @param serverUrl the URL to OSM server
    363      * @throws InterruptedException if we're interrupted while waiting for the event dispatching thread to finish OAuth authorization task
    364      * @throws InvocationTargetException if an exception is thrown while running OAuth authorization task
    365      * @since 12803
    366      */
    367     public static void obtainAccessToken(final URL serverUrl) throws InvocationTargetException, InterruptedException {
    368         final Runnable authTask = new FutureTask<>(() -> {
    369             // Concerning Utils.newDirectExecutor: Main worker cannot be used since this connection is already
    370             // executed via main worker. The OAuth connections would block otherwise.
    371             final OAuthAuthorizationWizard wizard = new OAuthAuthorizationWizard(
    372                     MainApplication.getMainFrame(),
    373                     AuthorizationProcedure.FULLY_AUTOMATIC,
    374                     serverUrl.toString(), Utils.newDirectExecutor(),
    375                     OAuthVersion.OAuth20, null);
    376             wizard.showDialog(null);
    377             return wizard;
    378         });
    379         // exception handling differs from implementation at GuiHelper.runInEDTAndWait()
    380         if (SwingUtilities.isEventDispatchThread()) {
    381             authTask.run();
    382         } else {
    383             SwingUtilities.invokeAndWait(authTask);
    384         }
    385     }
    386 
    387     class CancelAction extends AbstractAction {
    388 
    389         /**
    390          * Constructs a new {@code CancelAction}.
    391          */
    392         CancelAction() {
    393             putValue(NAME, tr("Cancel"));
    394             new ImageProvider("cancel").getResource().attachImageIcon(this);
    395             putValue(SHORT_DESCRIPTION, tr("Close the dialog and cancel authorization"));
    396         }
    397 
    398         public void cancel() {
    399             setCanceled(true);
    400             setVisible(false);
    401         }
    402 
    403         @Override
    404         public void actionPerformed(ActionEvent evt) {
    405             cancel();
    406         }
    407     }
    408 
    409     class AcceptAccessTokenAction extends AbstractAction implements PropertyChangeListener {
    410 
    411         /**
    412          * Constructs a new {@code AcceptAccessTokenAction}.
    413          */
    414         AcceptAccessTokenAction() {
    415             putValue(NAME, tr("Accept Access Token"));
    416             new ImageProvider("ok").getResource().attachImageIcon(this);
    417             putValue(SHORT_DESCRIPTION, tr("Close the dialog and accept the Access Token"));
    418             updateEnabledState(null);
    419         }
    420 
    421         @Override
    422         public void actionPerformed(ActionEvent evt) {
    423             setCanceled(false);
    424             setVisible(false);
    425         }
    426 
    427         /**
    428          * Update the enabled state
    429          * @param token The token to use
    430          * @since 18991
    431          */
    432         public final void updateEnabledState(IOAuthToken token) {
    433             setEnabled(token != null);
    434         }
    435 
    436         @Override
    437         public void propertyChange(PropertyChangeEvent evt) {
    438             if (!evt.getPropertyName().equals(AbstractAuthorizationUI.ACCESS_TOKEN_PROP))
    439                 return;
    440             updateEnabledState((IOAuthToken) evt.getNewValue());
    441         }
    442     }
    443 
    444     class WindowEventHandler extends WindowAdapter {
    445         @Override
    446         public void windowClosing(WindowEvent e) {
    447             new CancelAction().cancel();
    448         }
    449     }
    450 }
  • deleted file src/org/openstreetmap/josm/gui/oauth/OsmPrivilegesPanel.java

    diff --git src/org/openstreetmap/josm/gui/oauth/OsmPrivilegesPanel.java src/org/openstreetmap/josm/gui/oauth/OsmPrivilegesPanel.java
    deleted file mode 100644
    index 75fed5b180..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.openstreetmap.josm.tools.I18n.tr;
    5 
    6 import java.awt.GridBagConstraints;
    7 import java.awt.GridBagLayout;
    8 import java.awt.Insets;
    9 
    10 import javax.swing.BorderFactory;
    11 import javax.swing.JCheckBox;
    12 import javax.swing.JPanel;
    13 
    14 import org.openstreetmap.josm.data.oauth.OsmPrivileges;
    15 import org.openstreetmap.josm.gui.widgets.VerticallyScrollablePanel;
    16 
    17 /**
    18  * Panel letting the user choose from a detailed list of privileges that will be
    19  * requested for the OAuth token.
    20  */
    21 public class OsmPrivilegesPanel extends VerticallyScrollablePanel {
    22 
    23     private final JCheckBox cbWriteApi = new JCheckBox();
    24     private final JCheckBox cbWriteGpx = new JCheckBox();
    25     private final JCheckBox cbReadGpx = new JCheckBox();
    26     private final JCheckBox cbWritePrefs = new JCheckBox();
    27     private final JCheckBox cbReadPrefs = new JCheckBox();
    28     private final JCheckBox cbModifyNotes = new JCheckBox();
    29 
    30     /**
    31      * Constructs a new {@code OsmPrivilegesPanel}.
    32      */
    33     public OsmPrivilegesPanel() {
    34         build();
    35     }
    36 
    37     protected final void build() {
    38         setLayout(new GridBagLayout());
    39         GridBagConstraints gc = new GridBagConstraints();
    40         setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    41 
    42         // checkbox for "allow to upload map data"
    43         //
    44         gc.anchor = GridBagConstraints.NORTHWEST;
    45         gc.fill = GridBagConstraints.HORIZONTAL;
    46         gc.weightx = 1.0;
    47         gc.insets = new Insets(0, 0, 3, 3);
    48         add(cbWriteApi, gc);
    49         cbWriteApi.setText(tr("Allow to upload map data"));
    50         cbWriteApi.setToolTipText(tr("Select to grant JOSM the right to upload map data on your behalf"));
    51         cbWriteApi.setSelected(true);
    52 
    53         // checkbox for "allow to upload gps traces"
    54         //
    55         gc.gridy = 1;
    56         add(cbWriteGpx, gc);
    57         cbWriteGpx.setText(tr("Allow to upload GPS traces"));
    58         cbWriteGpx.setToolTipText(tr("Select to grant JOSM the right to upload GPS traces on your behalf"));
    59         cbWriteGpx.setSelected(true);
    60 
    61         // checkbox for "allow to download private gps traces"
    62         //
    63         gc.gridy = 2;
    64         add(cbReadGpx, gc);
    65         cbReadGpx.setText(tr("Allow to download your private GPS traces"));
    66         cbReadGpx.setToolTipText(tr("Select to grant JOSM the right to download your private GPS traces into JOSM layers"));
    67         cbReadGpx.setSelected(true);
    68 
    69         // checkbox for "allow to download private gps traces"
    70         //
    71         gc.gridy = 3;
    72         add(cbReadPrefs, gc);
    73         cbReadPrefs.setText(tr("Allow to read your preferences"));
    74         cbReadPrefs.setToolTipText(tr("Select to grant JOSM the right to read your server preferences"));
    75         cbReadPrefs.setSelected(true);
    76 
    77         // checkbox for "allow to download private gps traces"
    78         //
    79         gc.gridy = 4;
    80         add(cbWritePrefs, gc);
    81         cbWritePrefs.setText(tr("Allow to write your preferences"));
    82         cbWritePrefs.setToolTipText(tr("Select to grant JOSM the right to write your server preferences"));
    83         cbWritePrefs.setSelected(true);
    84 
    85         gc.gridy = 5;
    86         add(cbModifyNotes, gc);
    87         cbModifyNotes.setText(tr("Allow modifications of notes"));
    88         cbModifyNotes.setToolTipText(tr("Select to grant JOSM the right to modify notes on your behalf"));
    89         cbModifyNotes.setSelected(true);
    90 
    91         // filler - grab remaining space
    92         gc.gridy = 6;
    93         gc.fill = GridBagConstraints.BOTH;
    94         gc.weightx = 1.0;
    95         gc.weighty = 1.0;
    96         add(new JPanel(), gc);
    97     }
    98 
    99     /**
    100      * Replies the currently entered privileges
    101      *
    102      * @return the privileges
    103      */
    104     public OsmPrivileges getPrivileges() {
    105         OsmPrivileges privileges = new OsmPrivileges();
    106         privileges.setAllowWriteApi(cbWriteApi.isSelected());
    107         privileges.setAllowWriteGpx(cbWriteGpx.isSelected());
    108         privileges.setAllowReadGpx(cbReadGpx.isSelected());
    109         privileges.setAllowWritePrefs(cbWritePrefs.isSelected());
    110         privileges.setAllowReadPrefs(cbReadPrefs.isSelected());
    111         privileges.setAllowModifyNotes(cbModifyNotes.isSelected());
    112         return privileges;
    113     }
    114 }
  • src/org/openstreetmap/josm/gui/oauth/package-info.java

    diff --git src/org/openstreetmap/josm/gui/oauth/package-info.java src/org/openstreetmap/josm/gui/oauth/package-info.java
    index 658179245b..b25f6f817b 100644
     
    11// License: GPL. For details, see LICENSE file.
    22
    33/**
    4  * Provides GUI classes for handling OAuth authentication to OSM API.
    5  * Backend is <a href="https://github.com/mttkay/signpost">OAuth Signpost</a>.
     4 * Provides GUI classes for handling OAuth 2.0 authentication to the OSM API.
    65 */
    76package org.openstreetmap.josm.gui.oauth;
  • src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java

    diff --git src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java
    index f2792c6d43..2179028bed 100644
    import javax.swing.ButtonGroup;  
    1717import javax.swing.JPanel;
    1818import javax.swing.JRadioButton;
    1919
     20import org.openstreetmap.josm.actions.ExpertToggleAction;
    2021import org.openstreetmap.josm.data.UserIdentityManager;
    2122import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    2223import org.openstreetmap.josm.data.oauth.OAuthVersion;
    … … import org.openstreetmap.josm.tools.Logging;  
    3536 */
    3637public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel implements PropertyChangeListener {
    3738
     39    /** the choice of the authentication method; only shown to experts, see {@link #updateAuthenticationMethodVisibility()} */
     40    private final JPanel pnlAuthenticationMethod = new JPanel(new FlowLayout(FlowLayout.LEADING));
     41    /** follows expert mode; held here since {@link ExpertToggleAction} only keeps a weak reference to its listeners */
     42    private final transient ExpertToggleAction.ExpertModeChangeListener expertModeListener =
     43            isExpert -> updateAuthenticationMethodVisibility();
    3844    /** indicates whether we use basic authentication */
    3945    private final JRadioButton rbBasicAuthentication = new JRadioButton();
    4046    /** indicates whether we use OAuth 2.0 as authentication scheme */
    … … public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel im  
    6369
    6470        AuthenticationMethodChangeListener authChangeListener = new AuthenticationMethodChangeListener();
    6571
    66         JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
    6772        // -- radio button for basic authentication
    68         buttonPanel.add(rbBasicAuthentication);
     73        pnlAuthenticationMethod.add(rbBasicAuthentication);
    6974        rbBasicAuthentication.setText(tr("Use Basic Authentication"));
    7075        rbBasicAuthentication.setToolTipText(tr("Select to use HTTP basic authentication with your OSM username and password"));
    7176        rbBasicAuthentication.addItemListener(authChangeListener);
    7277        //-- radio button for OAuth 2.0
    73         buttonPanel.add(rbOAuth20);
     78        pnlAuthenticationMethod.add(rbOAuth20);
    7479        rbOAuth20.setSelected(true); // This must before adding the listener; otherwise, saveToPreferences is called prior to initFromPreferences
    7580        rbOAuth20.setText(tr("Use OAuth {0}", "2.0"));
    7681        rbOAuth20.setToolTipText(tr("Select to use OAuth {0} as authentication mechanism", "2.0"));
    7782        rbOAuth20.addItemListener(authChangeListener);
    7883
    79         add(buttonPanel, GBC.eol());
     84        add(pnlAuthenticationMethod, GBC.eol());
     85        ExpertToggleAction.addExpertModeChangeListener(expertModeListener);
    8086        //-- radio button for OAuth
    8187        ButtonGroup bg = new ButtonGroup();
    8288        bg.add(rbBasicAuthentication);
    … … public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel im  
    119125        }
    120126        pnlBasicAuthPreferences.initFromPreferences();
    121127        pnlOAuth20Preferences.initFromPreferences();
     128        updateAuthenticationMethodVisibility();
     129    }
     130
     131    /**
     132     * Shows the choice of the authentication method in expert mode only, since basic authentication is meant as a
     133     * quick way to test one's own server rather than for normal use. It is shown regardless while basic
     134     * authentication is selected, so that a profile using it does not lose sight of its own setting. Selecting
     135     * another method does not hide the choice straight away, which would take the option away under the mouse.
     136     */
     137    private void updateAuthenticationMethodVisibility() {
     138        pnlAuthenticationMethod.setVisible(ExpertToggleAction.isExpert() || rbBasicAuthentication.isSelected());
    122139    }
    123140
    124141    /**
    … … public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel im  
    132149        } else if (rbOAuth20.isSelected()) {
    133150            authMethod = "oauth20";
    134151        } else {
    135             throw new IllegalStateException("One of OAuth 2.0, OAuth 1.0a, or Basic authentication must be checked");
     152            throw new IllegalStateException("One of OAuth 2.0 or Basic authentication must be checked");
    136153        }
    137154        final boolean initUser = Config.getPref().put("osm-server.auth-method", authMethod);
    138155        if ("basic".equals(authMethod)) {
    … … public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel im  
    169186                pnlBasicAuthPreferences.revalidate();
    170187            } else if (rbOAuth20.isSelected()) {
    171188                pnlAuthenticationParameters.add(pnlOAuth20Preferences, BorderLayout.CENTER);
    172                 pnlOAuth20Preferences.saveToPreferences();
     189                // only refresh it: saving here would save what was entered before the user pressed OK
    173190                pnlOAuth20Preferences.initFromPreferences();
    174191                pnlOAuth20Preferences.revalidate();
    175192            }
    … … public class AuthenticationPreferencesPanel extends VerticallyScrollablePanel im  
    188205    }
    189206
    190207    /**
    191      * Update the acceptable authentications methods
     208     * Update the acceptable authentications methods: basic authentication is not offered for a server which is known
     209     * not to accept it, unless it is in use already, so that it can be changed.
    192210     * @param apiUrl The API url to check
    193211     */
    194212    private void updateAcceptableAuthenticationMethods(String apiUrl) {
    195213        final String authMethod = OsmApi.getAuthMethod();
    196         final boolean defaultApi = JosmUrls.getInstance().getDefaultOsmApiUrl().equals(apiUrl);
    197         rbBasicAuthentication.setEnabled(rbBasicAuthentication.isSelected() || "basic".equals(authMethod) || !defaultApi);
     214        rbBasicAuthentication.setEnabled(rbBasicAuthentication.isSelected() || "basic".equals(authMethod)
     215                || !isOAuthOnly(apiUrl));
     216    }
     217
     218    /**
     219     * Determines whether a server is known to accept OAuth 2.0 only, not basic authentication.
     220     * @param apiUrl The API url to check
     221     * @return {@code true} for the default OSM API and the OpenGeofiction API
     222     */
     223    private static boolean isOAuthOnly(String apiUrl) {
     224        final String url = OsmApi.normalizeApiUrl(apiUrl);
     225        return JosmUrls.getInstance().getDefaultOsmApiUrl().equals(url) || "https://opengeofiction.net/api".equals(url);
    198226    }
    199227
    200228}
  • src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java

    diff --git src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java
    index 1ceeea0347..11fc6bb6f8 100644
    import java.awt.GridBagConstraints;  
    1212import java.awt.GridBagLayout;
    1313import java.awt.Insets;
    1414import java.awt.event.ActionEvent;
    15 import java.awt.event.ItemEvent;
    1615import java.beans.PropertyChangeEvent;
    1716import java.beans.PropertyChangeListener;
    1817import java.net.URI;
    1918import java.net.URISyntaxException;
    2019import java.util.Arrays;
    21 import java.util.Objects;
    2220
    2321import javax.swing.AbstractAction;
    2422import javax.swing.BorderFactory;
    2523import javax.swing.JButton;
    2624import javax.swing.JCheckBox;
    27 import javax.swing.JLabel;
     25import javax.swing.JOptionPane;
    2826import javax.swing.JPanel;
    2927
    30 import org.openstreetmap.josm.actions.ExpertToggleAction;
     28import org.openstreetmap.josm.data.oauth.IOAuthParameters;
    3129import org.openstreetmap.josm.data.oauth.IOAuthToken;
     30import org.openstreetmap.josm.data.oauth.OAuth20Authorization;
    3231import org.openstreetmap.josm.data.oauth.OAuth20Token;
    3332import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    3433import org.openstreetmap.josm.data.oauth.OAuthParameters;
    3534import org.openstreetmap.josm.data.oauth.OAuthVersion;
     35import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
    3636import org.openstreetmap.josm.data.validation.routines.DomainValidator;
    3737import org.openstreetmap.josm.gui.MainApplication;
    3838import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel;
    39 import org.openstreetmap.josm.gui.oauth.AuthorizationProcedure;
    40 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    4139import org.openstreetmap.josm.gui.oauth.TestAccessTokenTask;
    4240import org.openstreetmap.josm.gui.util.GuiHelper;
    4341import org.openstreetmap.josm.gui.widgets.JMultilineLabel;
    44 import org.openstreetmap.josm.gui.widgets.JosmTextField;
    4542import org.openstreetmap.josm.io.OsmApi;
    4643import org.openstreetmap.josm.io.auth.CredentialsManager;
     44import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
    4745import org.openstreetmap.josm.tools.GBC;
    4846import org.openstreetmap.josm.tools.ImageProvider;
    4947import org.openstreetmap.josm.tools.Logging;
    50 import org.openstreetmap.josm.tools.UserCancelException;
    5148import org.openstreetmap.josm.tools.Utils;
    5249
    5350/**
    54  * The preferences panel for the OAuth 1.0a preferences. This just a summary panel
    55  * showing the current Access Token Key and Access Token Secret, if the
    56  * user already has an Access Token.
    57  * <br>
    58  * For initial authorisation see {@link OAuthAuthorizationWizard}.
     51 * The preferences panel for OAuth 2.0: whether JOSM has an Access Token for the server, a button to authorize JOSM
     52 * in the web browser, and the advanced OAuth parameters, which include the Access Token itself so that a token
     53 * obtained outside JOSM can be pasted instead.
    5954 * @since 2745
    6055 */
    6156public class OAuthAuthenticationPreferencesPanel extends JPanel implements PropertyChangeListener {
    6257    private final JCheckBox cbUseForAllRequests = new JCheckBox();
    63     private final JCheckBox cbShowAdvancedParameters = new JCheckBox(tr("Display Advanced OAuth Parameters"));
    6458    private final JCheckBox cbSaveToPreferences = new JCheckBox(tr("Save to preferences"));
    6559    private final JPanel pnlAuthorisationMessage = new JPanel(new BorderLayout());
    6660    private final NotYetAuthorisedPanel pnlNotYetAuthorised;
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    9488        cbUseForAllRequests.setToolTipText(tr("For user-based bandwidth limit instead of IP-based one"));
    9589        pnl.add(cbUseForAllRequests, GBC.eol().fill(GBC.HORIZONTAL));
    9690
    97         pnl.add(cbShowAdvancedParameters, GBC.eol().fill(GBC.HORIZONTAL));
    98         cbShowAdvancedParameters.setSelected(false);
    99         cbShowAdvancedParameters.addItemListener(
    100                 evt -> pnlAdvancedProperties.setVisible(evt.getStateChange() == ItemEvent.SELECTED)
    101         );
    102 
    10391        pnl.add(pnlAdvancedProperties, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 3, 0, 0));
    10492        pnlAdvancedProperties.initialize(OsmApi.getOsmApi().getServerUrl());
    10593        pnlAdvancedProperties.setBorder(
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    10896                        BorderFactory.createEmptyBorder(3, 3, 3, 3)
    10997                )
    11098        );
    111         pnlAdvancedProperties.setVisible(false);
    11299        pnlAdvancedProperties.addPropertyChangeListener(this);
    113100        return pnl;
    114101    }
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    118105     * advanced OAuth parameters changed.
    119106     */
    120107    private void updateAuthoriseNowActions() {
    121         for (JPanel panel : Arrays.asList(this.pnlNotYetAuthorised, (JPanel) this.pnlAlreadyAuthorised.getComponent(6))) {
     108        for (JPanel panel : Arrays.asList(this.pnlNotYetAuthorised, this.pnlAlreadyAuthorised.pnlButtons)) {
    122109            for (Component component : panel.getComponents()) {
    123110                if (component instanceof JButton && ((JButton) component).getAction() instanceof AuthoriseNowAction) {
    124111                    ((AuthoriseNowAction) ((JButton) component).getAction()).updateEnabledState();
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    144131
    145132    protected void refreshView() {
    146133        pnlAuthorisationMessage.removeAll();
     134        pnlAdvancedProperties.setAccessToken(getBearerToken());
    147135        if (OAuthAccessTokenHolder.getInstance().getAccessToken(this.apiUrl, this.oAuthVersion) != null) {
    148136            pnlAuthorisationMessage.add(pnlAlreadyAuthorised, BorderLayout.CENTER);
    149137            pnlAlreadyAuthorised.refreshView();
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    155143        repaint();
    156144    }
    157145
     146    /**
     147     * Get the bearer token JOSM currently has for the API.
     148     * @return the bearer token, or {@code null} if there is none
     149     */
     150    private String getBearerToken() {
     151        if (apiUrl == null) {
     152            return null;
     153        }
     154        final IOAuthToken token = OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion);
     155        return token instanceof OAuth20Token ? ((OAuth20Token) token).getBearerToken() : null;
     156    }
     157
     158    /**
     159     * Determines whether the user changed the access token in the advanced OAuth parameters.
     160     * @return {@code true} if the access token entered differs from the one JOSM has
     161     */
     162    private boolean isAccessTokenEdited() {
     163        final String current = getBearerToken();
     164        return apiUrl != null && !pnlAdvancedProperties.getAccessToken().equals(current == null ? "" : current);
     165    }
     166
     167    /**
     168     * Get the access token entered in the advanced OAuth parameters: a token issued outside JOSM, pasted instead of
     169     * authorizing JOSM. It works with nothing else, so it is a way to authenticate when authorizing JOSM is not
     170     * possible.
     171     * @return the token, or {@code null} if none is entered
     172     */
     173    private IOAuthToken getEnteredAccessToken() {
     174        final String entered = pnlAdvancedProperties.getAccessToken();
     175        return entered.isEmpty() ? null : OAuth20Token.fromAccessToken(pnlAdvancedProperties.getDisplayedParameters(), entered);
     176    }
     177
     178    /**
     179     * Takes over the access token entered in the advanced OAuth parameters, or removes the token if the field was
     180     * cleared. This is done when the preferences are saved, so that cancelling them leaves the token as it was. A
     181     * token which was not changed is left as it is, so that for example its refresh token is kept.
     182     */
     183    private void applyEnteredAccessToken() {
     184        if (isAccessTokenEdited()) {
     185            OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, getEnteredAccessToken());
     186        }
     187    }
     188
    158189    /**
    159190     * Sets the URL of the OSM API for which this panel is currently displaying OAuth properties.
    160191     *
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    179210     * Saves the current values to preferences
    180211     */
    181212    public void saveToPreferences() {
     213        applyEnteredAccessToken();
    182214        OAuthAccessTokenHolder.getInstance().setSaveToPreferences(cbSaveToPreferences.isSelected());
    183215        OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
    184216        OsmApi.USE_OAUTH_FOR_ALL_REQUESTS.put(cbUseForAllRequests.isSelected());
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    208240            lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
    209241
    210242            // Action for authorising now
    211             add(new JButton(new AuthoriseNowAction(AuthorizationProcedure.FULLY_AUTOMATIC)), GBC.eol());
    212             JButton authManually = new JButton(new AuthoriseNowAction(AuthorizationProcedure.MANUALLY));
    213             add(authManually, GBC.eol());
    214             ExpertToggleAction.addVisibilitySwitcher(authManually);
     243            add(new JButton(new AuthoriseNowAction()), GBC.eol());
    215244
    216245            // filler - grab remaining space
    217246            add(new JPanel(), GBC.std().fill(GBC.BOTH));
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    223252     *
    224253     */
    225254    private class AlreadyAuthorisedPanel extends JPanel {
    226         private final JosmTextField tfAccessTokenKey = new JosmTextField(null, null, 0, false);
     255        private final JPanel pnlButtons = new JPanel(new FlowLayout(FlowLayout.LEFT));
    227256
    228257        /**
    229258         * Constructs a new {@code AlreadyAuthorisedPanel}.
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    245274            add(lbl, gc);
    246275            lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
    247276
    248             // -- access token key
     277            // -- save to preferences; the Access Token itself is shown with the advanced OAuth parameters
    249278            gc.gridy = 1;
    250279            gc.gridx = 0;
    251             gc.gridwidth = 1;
    252             gc.weightx = 0.0;
    253             add(new JLabel(tr("Access Token Key:")), gc);
    254 
    255             gc.gridx = 1;
    256             gc.weightx = 1.0;
    257             add(tfAccessTokenKey, gc);
    258             tfAccessTokenKey.setEditable(false);
    259 
    260             // -- access token secret
    261             gc.gridy = 2;
    262             gc.gridx = 0;
    263             gc.gridwidth = 1;
    264             gc.weightx = 0.0;
    265             add(new JLabel(tr("Access Token Secret:")), gc);
    266 
    267             // -- access token secret
    268             gc.gridy = 3;
    269             gc.gridx = 0;
    270280            gc.gridwidth = 2;
    271281            gc.weightx = 1.0;
    272282            add(cbSaveToPreferences, gc);
    273283            cbSaveToPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences());
    274284
    275285            // -- action buttons
    276             JPanel btns = new JPanel(new FlowLayout(FlowLayout.LEFT));
    277             btns.add(new JButton(new RenewAuthorisationAction(AuthorizationProcedure.FULLY_AUTOMATIC)));
    278             btns.add(new JButton(new TestAuthorisationAction()));
    279             btns.add(new JButton(new RemoveAuthorisationAction()));
    280             gc.gridy = 4;
     286            pnlButtons.add(new JButton(new RenewAuthorisationAction()));
     287            pnlButtons.add(new JButton(new TestAuthorisationAction()));
     288            pnlButtons.add(new JButton(new RemoveAuthorisationAction()));
     289            gc.gridy = 2;
    281290            gc.gridx = 0;
    282291            gc.gridwidth = 2;
    283292            gc.weightx = 1.0;
    284             add(btns, gc);
     293            add(pnlButtons, gc);
    285294
    286295            // filler - grab the remaining space
    287             gc.gridy = 6;
     296            gc.gridy = 3;
    288297            gc.fill = GridBagConstraints.BOTH;
    289298            gc.weightx = 1.0;
    290299            gc.weighty = 1.0;
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    292301        }
    293302
    294303        protected final void refreshView() {
    295             switch (oAuthVersion) {
    296                 case OAuth20:
    297                 case OAuth21:
    298                     String token = "";
    299                     if (apiUrl != null) {
    300                         OAuth20Token bearerToken = (OAuth20Token) OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion);
    301                         token = bearerToken == null ? "" : bearerToken.getBearerToken();
    302                     }
    303                     tfAccessTokenKey.setText(token == null ? "" : token);
    304                     break;
    305                 default:
    306             }
    307304            cbSaveToPreferences.setSelected(OAuthAccessTokenHolder.getInstance().isSaveToPreferences());
    308305        }
    309306    }
    310307
    311308    /**
    312      * Action to authorise the current user
     309     * Action to authorise the current user: JOSM is authorized in the web browser, with the OAuth parameters
     310     * currently shown, and receives an Access Token by remote control.
    313311     */
    314312    private class AuthoriseNowAction extends AbstractAction {
    315         private final AuthorizationProcedure procedure;
    316 
    317         AuthoriseNowAction(AuthorizationProcedure procedure) {
    318             this.procedure = procedure;
    319             putValue(NAME, tr("{0} ({1})", tr("Authorize now"), procedure.getText()));
    320             putValue(SHORT_DESCRIPTION, procedure.getDescription());
    321             if (procedure == AuthorizationProcedure.FULLY_AUTOMATIC) {
    322                 new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
    323             }
     313        /** Counts the updates of the enabled state, so that the result of an earlier one cannot override a later one */
     314        private int updates;
     315
     316        AuthoriseNowAction() {
     317            putValue(NAME, tr("Authorize now"));
     318            putValue(SHORT_DESCRIPTION, tr("Authorize JOSM in the web browser to access the OSM server on your behalf, "
     319                    + "and get an Access Token"));
     320            new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
    324321            updateEnabledState();
    325322        }
    326323
    327324        void updateEnabledState() {
    328             if (procedure == AuthorizationProcedure.MANUALLY) {
    329                 this.setEnabled(true);
    330             } else if (!pnlAdvancedProperties.isUseDefaultSettings()) {
     325            final int update = ++updates;
     326            if (!pnlAdvancedProperties.isUseDefaultSettings()) {
    331327                // The user supplied the parameters - the client id of an OAuth application they
    332                 // registered on the server themselves. The wizard is given exactly these parameters
     328                // registered on the server themselves. Authorization uses exactly these parameters
    333329                // when the button is pressed, so they decide whether it can be pressed.
    334330                this.setEnabled(!Utils.isEmpty(pnlAdvancedProperties.getEnteredClientId()));
    335331            } else if (Utils.isValidUrl(apiUrl)) {
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    341337                    return;
    342338                }
    343339                if (DomainValidator.getInstance().isValid(apiURI.getHost())) {
    344                     // We want to avoid trying to make connection with an invalid URL
     340                    // We want to avoid trying to make connection with an invalid URL. These are the parameters
     341                    // authorization uses, see AdvancedOAuthPropertiesPanel.getAdvancedParameters().
    345342                    final String currentApiUrl = apiUrl;
    346343                    MainApplication.worker.execute(() -> {
    347                         final String clientId = OAuthParameters.createFromApiUrl(apiUrl, oAuthVersion).getClientId();
    348                         if (Objects.equals(apiUrl, currentApiUrl)) {
    349                             GuiHelper.runInEDT(() -> this.setEnabled(!Utils.isEmpty(clientId)));
    350                         }
     344                        final String clientId = OAuthParameters.createDefault(currentApiUrl, oAuthVersion).getClientId();
     345                        GuiHelper.runInEDT(() -> {
     346                            if (update == updates) {
     347                                this.setEnabled(!Utils.isEmpty(clientId));
     348                            }
     349                        });
    351350                    });
    352351                }
    353352            }
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    355354
    356355        @Override
    357356        public void actionPerformed(ActionEvent arg0) {
    358             OAuthAuthorizationWizard wizard = new OAuthAuthorizationWizard(
    359                     OAuthAuthenticationPreferencesPanel.this,
    360                     procedure,
    361                     apiUrl,
    362                     MainApplication.worker,
    363                     oAuthVersion,
    364                     pnlAdvancedProperties.getAdvancedParameters()
    365                     );
    366             try {
    367                 wizard.showDialog(token -> GuiHelper.runInEDT(OAuthAuthenticationPreferencesPanel.this::refreshView));
    368             } catch (UserCancelException userCancelException) {
    369                 Logging.trace(userCancelException);
    370                 return;
     357            final String currentApiUrl = apiUrl;
     358            final IOAuthParameters parameters = pnlAdvancedProperties.getAdvancedParameters();
     359            // the token is received by remote control, which is started for the time it takes if it is not running
     360            final boolean remoteControlIsRunning = Boolean.TRUE.equals(RemoteControl.PROP_REMOTECONTROL_ENABLED.get());
     361            if (!remoteControlIsRunning) {
     362                RemoteControl.start();
    371363            }
    372             pnlAdvancedProperties.setAdvancedParameters(wizard.getOAuthParameters());
    373             refreshView();
     364            new OAuth20Authorization().authorize(parameters, token -> {
     365                if (!remoteControlIsRunning) {
     366                    RemoteControl.stop();
     367                }
     368                // a failed attempt, e.g. at a new token, leaves the token JOSM has as it is
     369                token.ifPresent(t -> {
     370                    OAuthAccessTokenHolder.getInstance().setAccessToken(currentApiUrl, t);
     371                    OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
     372                });
     373                GuiHelper.runInEDT(() -> {
     374                    if (!token.isPresent()) {
     375                        JOptionPane.showMessageDialog(OAuthAuthenticationPreferencesPanel.this,
     376                                tr("Authentication failed, please check browser for details."),
     377                                tr("OAuth Authentication Failed"),
     378                                JOptionPane.ERROR_MESSAGE);
     379                    }
     380                    refreshView();
     381                });
     382            }, OsmScopes.getJosmScopes());
    374383        }
    375384    }
    376385
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    393402    }
    394403
    395404    /**
    396      * Launches the OAuthAuthorisationWizard to generate a new Access Token
     405     * Authorizes JOSM again, to generate a new Access Token
    397406     */
    398407    private class RenewAuthorisationAction extends AuthoriseNowAction {
    399408        /**
    400409         * Constructs a new {@code RenewAuthorisationAction}.
    401410         */
    402         RenewAuthorisationAction(AuthorizationProcedure procedure) {
    403             super(procedure);
     411        RenewAuthorisationAction() {
    404412            putValue(NAME, tr("New Access Token"));
    405413            putValue(SHORT_DESCRIPTION, tr("Click to step through the OAuth authorization process and generate a new Access Token"));
    406             new ImageProvider("oauth", "oauth-small").getResource().attachImageIcon(this);
    407414        }
    408415    }
    409416
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    422429
    423430        @Override
    424431        public void actionPerformed(ActionEvent evt) {
    425             IOAuthToken token = OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, OAuthVersion.OAuth20);
     432            // a token pasted but not saved yet is what the user wants to know about, and none if the field was cleared
     433            final IOAuthToken token = isAccessTokenEdited() ? getEnteredAccessToken()
     434                    : OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, oAuthVersion);
     435            if (token == null) {
     436                JOptionPane.showMessageDialog(OAuthAuthenticationPreferencesPanel.this,
     437                        tr("There is no Access Token to test."), tr("Test Access Token"), JOptionPane.INFORMATION_MESSAGE);
     438                return;
     439            }
    426440            TestAccessTokenTask task = new TestAccessTokenTask(
    427441                    OAuthAuthenticationPreferencesPanel.this,
    428442                    apiUrl,
    … … public class OAuthAuthenticationPreferencesPanel extends JPanel implements Prope  
    436450    public void propertyChange(PropertyChangeEvent evt) {
    437451        if (AdvancedOAuthPropertiesPanel.PARAMETERS_CHANGED_PROP.equals(evt.getPropertyName())) {
    438452            updateAuthoriseNowActions();
     453
    439454        } else if (OsmApiUrlInputPanel.API_URL_PROP.equals(evt.getPropertyName())) {
    440455            setApiUrl((String) evt.getNewValue());
     456            refreshView();
    441457        }
    442458    }
    443459}
  • src/org/openstreetmap/josm/io/MissingOAuthAccessTokenException.java

    diff --git src/org/openstreetmap/josm/io/MissingOAuthAccessTokenException.java src/org/openstreetmap/josm/io/MissingOAuthAccessTokenException.java
    index 44466f33ec..85a50a8021 100644
    package org.openstreetmap.josm.io;  
    66 */
    77public class MissingOAuthAccessTokenException extends OsmTransferException {
    88
     9    /** the API URL of the server JOSM has no OAuth client id for, so that it could not obtain an access token */
     10    private final String clientIdMissingFor;
     11
    912    /**
    1013     * Constructs a new {@code MissingOAuthAccessTokenException}.
    1114     */
    1215    public MissingOAuthAccessTokenException() {
    1316        super();
     17        this.clientIdMissingFor = null;
    1418    }
    1519
    1620    /**
    … … public class MissingOAuthAccessTokenException extends OsmTransferException {  
    2125     */
    2226    public MissingOAuthAccessTokenException(String message, Throwable cause) {
    2327        super(message, cause);
     28        this.clientIdMissingFor = null;
    2429    }
    2530
    2631    /**
    … … public class MissingOAuthAccessTokenException extends OsmTransferException {  
    2934     */
    3035    public MissingOAuthAccessTokenException(String message) {
    3136        super(message);
     37        this.clientIdMissingFor = null;
     38    }
     39
     40    private MissingOAuthAccessTokenException(String message, String clientIdMissingFor) {
     41        super(message);
     42        this.clientIdMissingFor = clientIdMissingFor;
    3243    }
    3344
    3445    /**
    … … public class MissingOAuthAccessTokenException extends OsmTransferException {  
    3849     */
    3950    public MissingOAuthAccessTokenException(Throwable cause) {
    4051        super(cause);
     52        this.clientIdMissingFor = null;
     53    }
     54
     55    /**
     56     * Creates the exception for a server JOSM has no OAuth client id for, so that it cannot obtain an access token:
     57     * the user has to enter the client id of an OAuth application registered on the server, or an access token.
     58     * @param apiUrl the API URL of the server
     59     * @return the exception
     60     * @since xxx
     61     */
     62    public static MissingOAuthAccessTokenException clientIdMissing(String apiUrl) {
     63        return new MissingOAuthAccessTokenException("No OAuth client id for " + apiUrl + ", cannot request a token", apiUrl);
     64    }
     65
     66    /**
     67     * Determines whether JOSM has no OAuth client id for the server, which is why it has no access token.
     68     * @return {@code true} if the client id is missing
     69     * @since xxx
     70     */
     71    public boolean isClientIdMissing() {
     72        return clientIdMissingFor != null;
     73    }
     74
     75    /**
     76     * Get the API URL of the server JOSM has no OAuth client id for.
     77     * @return the API URL, or {@code null} unless {@link #isClientIdMissing()}
     78     * @since xxx
     79     */
     80    public String getClientIdMissingFor() {
     81        return clientIdMissingFor;
    4182    }
    4283}
  • src/org/openstreetmap/josm/io/OsmConnection.java

    diff --git src/org/openstreetmap/josm/io/OsmConnection.java src/org/openstreetmap/josm/io/OsmConnection.java
    index 184cf2272d..c369cb2432 100644
    package org.openstreetmap.josm.io;  
    33
    44import static org.openstreetmap.josm.tools.I18n.tr;
    55
    6 import java.lang.reflect.InvocationTargetException;
    76import java.net.Authenticator.RequestorType;
    8 import java.net.URL;
    97import java.nio.charset.StandardCharsets;
    108import java.util.Base64;
    119import java.util.Objects;
    … … import org.openstreetmap.josm.io.auth.CredentialsAgentResponse;  
    3129import org.openstreetmap.josm.io.auth.CredentialsManager;
    3230import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
    3331import org.openstreetmap.josm.tools.HttpClient;
    34 import org.openstreetmap.josm.tools.JosmRuntimeException;
    3532import org.openstreetmap.josm.tools.Logging;
    3633import org.openstreetmap.josm.tools.Utils;
    3734
    … … public class OsmConnection {  
    4946    protected HttpClient activeConnection;
    5047    protected IOAuthParameters oAuth20Parameters;
    5148
    52     /**
    53      * Retrieves OAuth access token.
    54      * @since 12803
    55      */
    56     @FunctionalInterface
    57     public interface OAuthAccessTokenFetcher {
    58         /**
    59          * Obtains an OAuth access token for the connection. Afterwards, the token is accessible via {@link OAuthAccessTokenHolder}.
    60          * @param serverUrl the URL to OSM server
    61          * @throws InterruptedException if we're interrupted while waiting for the event dispatching thread to finish OAuth authorization task
    62          * @throws InvocationTargetException if an exception is thrown while running OAuth authorization task
    63          */
    64         void obtainAccessToken(URL serverUrl) throws InvocationTargetException, InterruptedException;
    65     }
    66 
    67     static volatile OAuthAccessTokenFetcher fetcher = u -> {
    68         throw new JosmRuntimeException("OsmConnection.setOAuthAccessTokenFetcher() has not been called");
    69     };
    70 
    71     /**
    72      * Sets the OAuth access token fetcher.
    73      * @param tokenFetcher new OAuth access token fetcher. Cannot be null
    74      * @since 12803
    75      */
    76     public static void setOAuthAccessTokenFetcher(OAuthAccessTokenFetcher tokenFetcher) {
    77         fetcher = Objects.requireNonNull(tokenFetcher, "tokenFetcher");
    78     }
    79 
    8049    /**
    8150     * Cancels the connection.
    8251     */
    … … public class OsmConnection {  
    149118    private void obtainOAuth20Token() throws MissingOAuthAccessTokenException {
    150119        if (Utils.isEmpty(this.oAuth20Parameters.getClientId())) {
    151120            // Without a client id the authorization request is rejected by the server with "Missing required
    152             // parameter: client_id", so do not send the user to the browser at all. The message of the exception
    153             // is for the log only; what the user is shown already points at the preferences, which is where the
    154             // client id of an OAuth application registered on this server has to be entered.
    155             throw new MissingOAuthAccessTokenException(
    156                     "No OAuth client id for " + OsmApi.getOsmApi().getServerUrl() + ", cannot request a token");
     121            // parameter: client_id", so do not send the user to the browser at all, but tell them what is missing.
     122            throw MissingOAuthAccessTokenException.clientIdMissing(OsmApi.getOsmApi().getServerUrl());
    157123        }
    158124        if (!Boolean.TRUE.equals(GuiHelper.runInEDTAndWaitAndReturn(() ->
    159125                ConditionalOptionPaneUtil.showConfirmationDialog("oauth.oauth20.obtain.automatically",
    … … public class OsmConnection {  
    179145                    done.countDown();
    180146                };
    181147        new OAuth20Authorization().authorize(oAuth20Parameters,
    182                 consumer, OsmScopes.read_gpx, OsmScopes.write_gpx,
    183                 OsmScopes.read_prefs, OsmScopes.write_prefs,
    184                 OsmScopes.write_api, OsmScopes.write_notes);
    185         // Only wait at most 5 minutes
    186         int counter = 0;
    187         while (done.getCount() >= 0 && counter < 5) {
    188             try {
    189                 if (done.await(1, TimeUnit.MINUTES)) {
    190                     break;
    191                 }
    192             } catch (InterruptedException e) {
    193                 Thread.currentThread().interrupt();
    194                 Logging.trace(e);
    195                 consumer.accept(null);
    196                 throw new MissingOAuthAccessTokenException(e);
     148                consumer, OsmScopes.getJosmScopes());
     149        // Only wait at most 5 minutes for the user to authorize JOSM in the web browser
     150        try {
     151            if (!done.await(5, TimeUnit.MINUTES)) {
     152                Logging.warn("No OAuth access token received from {0} within 5 minutes", OsmApi.getOsmApi().getServerUrl());
    197153            }
    198             counter++;
     154        } catch (InterruptedException e) {
     155            Thread.currentThread().interrupt();
     156            Logging.trace(e);
     157            consumer.accept(Optional.empty());
     158            throw new MissingOAuthAccessTokenException(e);
    199159        }
    200160    }
    201161
    … … public class OsmConnection {  
    209169     */
    210170    protected void addOAuth20AuthorizationHeader(HttpClient connection) throws OsmTransferException {
    211171        if (this.oAuth20Parameters == null) {
    212             // The parameters are stored under the API URL, so look them up with the API URL and not with the
    213             // host of the request: OAuthParameters.createFromApiUrl() reduces it to the host itself where that
    214             // is what it needs.
     172            // Look them up with the API URL and not with the host of the request: OAuthParameters.createFromApiUrl()
     173            // reduces it to the host itself for the stored parameters, and needs the URL for the default ones.
    215174            this.oAuth20Parameters = OAuthParameters.createFromApiUrl(OsmApi.getOsmApi().getServerUrl(), OAuthVersion.OAuth20);
    216175        }
    217176        OAuthAccessTokenHolder holder = OAuthAccessTokenHolder.getInstance();
    218177        IOAuthToken token = holder.getAccessToken(connection.getURL().toExternalForm(), OAuthVersion.OAuth20);
    219         if (token == null) {
     178        // A token is obtained for the API, and so is only found for requests to the host of the API
     179        if (token == null && Objects.equals(connection.getURL().getHost(), OsmApi.getOsmApi().getHost())) {
    220180            obtainOAuth20Token();
    221181            token = holder.getAccessToken(connection.getURL().toExternalForm(), OAuthVersion.OAuth20);
    222182        }
    223         if (token == null) { // check if wizard completed
     183        if (token == null) { // check if authorization completed
    224184            throw new MissingOAuthAccessTokenException();
    225185        }
    226186        try {
  • src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java

    diff --git src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java
    index b23f2012e8..da46fa475a 100644
    public class JosmPreferencesCredentialAgent extends AbstractCredentialsAgent {  
    132132        if (accessToken == null) {
    133133            Set<String> keySet = new HashSet<>(Config.getPref().getKeySet());
    134134            keySet.addAll(Config.getPref().getSensitive()); // Just in case we decide to not return sensitive keys in getKeySet
    135             // Assume we want to remove all access tokens
     135            // Assume we want to remove all access tokens. The parameters stay: they are also the OAuth settings the
     136            // user entered for the server, which are needed to obtain the next token.
    136137            for (OAuthVersion oauthType : OAuthVersion.values()) {
    137138                final String hostKey = "oauth.access-token.object." + oauthType + "." + host;
    138                 final String parametersKey = "oauth.access-token.parameters." + oauthType + "." + host;
    139139                if (keySet.contains(hostKey)) {
    140140                    Config.getPref().removeSensitive(hostKey);
    141141                }
    142                 if (keySet.contains(parametersKey)) {
    143                     Config.getPref().removeSensitive(parametersKey);
    144                 }
    145142            }
    146143        } else {
    147144            final String hostKey = "oauth.access-token.object." + accessToken.getOAuthType() + "." + host;
    148145            final String parametersKey = "oauth.access-token.parameters." + accessToken.getOAuthType() + "." + host;
    149             Config.getPref().put(hostKey, accessToken.toPreferencesString());
     146            // the parameters first: listeners of the token, like UserIdentityManager, find them in place
    150147            Config.getPref().put(parametersKey, accessToken.getParameters().toPreferencesString());
    151             Config.getPref().addSensitive(this, hostKey);
    152148            Config.getPref().addSensitive(this, parametersKey);
     149            Config.getPref().put(hostKey, accessToken.toPreferencesString());
     150            Config.getPref().addSensitive(this, hostKey);
    153151        }
    154152    }
    155153
  • src/org/openstreetmap/josm/tools/ExceptionUtil.java

    diff --git src/org/openstreetmap/josm/tools/ExceptionUtil.java src/org/openstreetmap/josm/tools/ExceptionUtil.java
    index 34711a93b0..acac60d06a 100644
    public final class ExceptionUtil {  
    8383     */
    8484    public static String explainMissingOAuthAccessTokenException(MissingOAuthAccessTokenException e) {
    8585        Logging.error(e);
     86        if (e.isClientIdMissing()) {
     87            return tr(
     88                    "<html>Failed to authenticate at the OSM server ''{0}''.<br>"
     89                    + "JOSM cannot obtain an OAuth Access Token for this server, because it has no OAuth Client ID for it.<br>"
     90                    + "Please register an OAuth 2.0 application on the server, and enter its Client ID in the OAuth<br>"
     91                    + "settings of the Preferences Dialog; or enter an Access Token obtained outside JOSM there."
     92                    + "</html>",
     93                    e.getClientIdMissingFor()
     94            );
     95        }
    8696        return tr(
    8797                "<html>Failed to authenticate at the OSM server ''{0}''.<br>"
    8898                + "You are using OAuth to authenticate but currently there is no<br>"
  • test/unit/org/openstreetmap/josm/data/PreferencesTest.java

    diff --git test/unit/org/openstreetmap/josm/data/PreferencesTest.java test/unit/org/openstreetmap/josm/data/PreferencesTest.java
    index 0ffb4d152f..9a10a59a99 100644
     
    22package org.openstreetmap.josm.data;
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertNull;
     6
     7import java.io.File;
     8import java.io.IOException;
     9import java.nio.charset.StandardCharsets;
     10import java.nio.file.Files;
     11import java.nio.file.Path;
     12
     13import javax.xml.stream.XMLStreamException;
    514
    615import org.junit.jupiter.api.Test;
     16import org.junit.jupiter.api.io.TempDir;
     17import org.openstreetmap.josm.spi.preferences.IBaseDirectories;
    718import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    819import org.openstreetmap.josm.testutils.annotations.OsmApi;
     20import org.xml.sax.SAXException;
    921
    1022/**
    1123 * Unit tests of {@link Preferences}.
    … … class PreferencesTest {  
    2537            "</preferences>%n", Version.getInstance().getVersion()),
    2638                Preferences.main().toXML(true));
    2739    }
     40
     41    /**
     42     * The OAuth 1.0a access token, which nothing has used since OAuth 1.0a was removed, is deleted from the
     43     * preferences when they are loaded, so that it does not stay on disk indefinitely.
     44     * @param dir a temporary directory for the preferences file
     45     * @throws IOException if the preferences file cannot be written or read
     46     * @throws SAXException if the preferences file is not valid
     47     * @throws XMLStreamException if the preferences file cannot be parsed
     48     */
     49    @Test
     50    void testObsoleteOAuth10aTokenIsRemoved(@TempDir Path dir) throws IOException, SAXException, XMLStreamException {
     51        Files.write(dir.resolve("preferences.xml"), String.format(
     52            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>%n" +
     53            "<preferences xmlns='http://josm.openstreetmap.de/preferences-1.0' version='19000'>%n" +
     54            "  <tag key='oauth.access-token.key' value='an-old-key'/>%n" +
     55            "  <tag key='oauth.access-token.secret' value='an-old-secret'/>%n" +
     56            "  <tag key='osm-server.url' value='http://fake.xxx/api'/>%n" +
     57            "</preferences>%n").getBytes(StandardCharsets.UTF_8));
     58        final File directory = dir.toFile();
     59        final Preferences preferences = new Preferences(new IBaseDirectories() {
     60            @Override
     61            public File getPreferencesDirectory(boolean createIfMissing) {
     62                return directory;
     63            }
     64
     65            @Override
     66            public File getUserDataDirectory(boolean createIfMissing) {
     67                return directory;
     68            }
     69
     70            @Override
     71            public File getCacheDirectory(boolean createIfMissing) {
     72                return directory;
     73            }
     74        });
     75        preferences.load();
     76
     77        assertNull(preferences.get("oauth.access-token.key", null));
     78        assertNull(preferences.get("oauth.access-token.secret", null));
     79        assertEquals("http://fake.xxx/api", preferences.get("osm-server.url", null));
     80    }
    2881}
  • test/unit/org/openstreetmap/josm/data/UserIdentityManagerTest.java

    diff --git test/unit/org/openstreetmap/josm/data/UserIdentityManagerTest.java test/unit/org/openstreetmap/josm/data/UserIdentityManagerTest.java
    index 4bb4d5fd39..b5003be1a8 100644
    import static org.junit.jupiter.api.Assertions.fail;  
    1313import java.util.function.Function;
    1414import java.util.stream.Stream;
    1515
     16import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
     17import org.openstreetmap.josm.data.oauth.OAuth20Token;
     18import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    1619import org.openstreetmap.josm.data.osm.User;
    1720import org.openstreetmap.josm.data.osm.UserInfo;
     21import org.openstreetmap.josm.io.NetworkManager;
     22import org.openstreetmap.josm.io.OnlineResource;
     23import org.openstreetmap.josm.io.OsmApi;
     24import org.openstreetmap.josm.io.auth.CredentialsManager;
    1825import org.openstreetmap.josm.spi.preferences.Config;
    1926import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    2027
    … … class UserIdentityManagerTest {  
    4047        return userInfo;
    4148    }
    4249
     50    /**
     51     * Removing the OAuth token of the server makes the user anonymous.
     52     * <p>
     53     * Non-regression test: the identity followed the parameters stored with the token, which are kept since they
     54     * are the OAuth settings of the server too, so the user stayed identified after "Remove token".
     55     * @throws Exception if the token cannot be stored
     56     */
     57    @Test
     58    void testRemovingTheOAuthTokenMakesTheUserAnonymous() throws Exception {
     59        // fetching the user details once a token is stored must not make a network request
     60        NetworkManager.setOffline(OnlineResource.ALL);
     61        Config.getPref().put("osm-server.auth-method", "oauth20");
     62        final String apiUrl = OsmApi.getOsmApi().getServerUrl();
     63        final String host = OsmApi.getOsmApi().getHost();
     64        try {
     65            OAuthAccessTokenHolder.getInstance().clear();
     66            CredentialsManager.getInstance().storeOAuthAccessToken(host, new OAuth20Token(
     67                    new OAuth20Parameters("", null, "", "", apiUrl, ""), "{\"access_token\": \"a-token\", \"token_type\": \"bearer\"}"));
     68            UserIdentityManager.getInstance().setPartiallyIdentified("a-user");
     69
     70            // what "Remove token" in the preferences does
     71            OAuthAccessTokenHolder.getInstance().setAccessToken(apiUrl, null);
     72            OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
     73
     74            assertTrue(UserIdentityManager.getInstance().isAnonymous());
     75        } finally {
     76            Config.getPref().removeSensitive("oauth.access-token.parameters.OAuth20." + host);
     77            Config.getPref().put("osm-server.auth-method", null);
     78            OAuthAccessTokenHolder.getInstance().clear();
     79            NetworkManager.setOnline(OnlineResource.ALL);
     80            UserIdentityManager.getInstance().setAnonymous();
     81        }
     82    }
     83
    4384    /**
    4485     * Test singleton access.
    4586     */
  • test/unit/org/openstreetmap/josm/data/oauth/OAuthParametersTest.java

    diff --git test/unit/org/openstreetmap/josm/data/oauth/OAuthParametersTest.java test/unit/org/openstreetmap/josm/data/oauth/OAuthParametersTest.java
    index 24ab07f7fd..cff76a9eef 100644
     
    22package org.openstreetmap.josm.data.oauth;
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
    56import static org.junit.jupiter.api.Assertions.assertNotEquals;
    67import static org.junit.jupiter.api.Assertions.assertNotNull;
     8import static org.junit.jupiter.api.Assertions.assertNull;
     9import static org.junit.jupiter.api.Assertions.assertTrue;
    710
    811import org.junit.jupiter.api.AfterEach;
    912import org.junit.jupiter.api.Test;
    … … import org.openstreetmap.josm.spi.preferences.Config;  
    1417import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    1518import org.openstreetmap.josm.tools.Logging;
    1619
     20import com.github.tomakehurst.wiremock.WireMockServer;
     21import com.github.tomakehurst.wiremock.client.WireMock;
     22import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
     23
    1724import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
    1825import nl.jqno.equalsverifier.EqualsVerifier;
    1926
    … … import nl.jqno.equalsverifier.EqualsVerifier;  
    2330@BasicPreferences
    2431class OAuthParametersTest {
    2532
     33    private static final String THIRD_PARTY = "https://nonprod-mapops.example.org/api";
     34    private static final String THIRD_PARTY_HOST = "nonprod-mapops.example.org";
     35    private static final String OHM = "https://api.openhistoricalmap.org/api";
     36    private static final String REDIRECT_URI = "http://127.0.0.1:8111/oauth_authorization";
     37
    2638    @AfterEach
    2739    void tearDown() {
    2840        NetworkManager.setOnline(OnlineResource.ALL);
    29         // the API URL is static state shared with the other tests of this class
     41        // the preferences are static state shared with the other tests of this class
    3042        Config.getPref().put("osm-server.url", null);
     43        for (String key : new String[] {THIRD_PARTY_HOST, THIRD_PARTY, "api.openhistoricalmap.org"}) {
     44            Config.getPref().put("oauth.access-token.parameters.OAuth20." + key, null);
     45            Config.getPref().put("oauth.settings.use-default." + key, null);
     46        }
     47        Config.getPref().put("oauth.settings.use-default", null);
     48    }
     49
     50    private static OAuth20Parameters enteredParameters(String apiUrl, String clientId) {
     51        return new OAuth20Parameters(clientId, null, apiUrl, apiUrl, REDIRECT_URI);
     52    }
     53
     54    private static String clientIdOf(String apiUrl) {
     55        return OAuthParameters.createFromApiUrl(apiUrl, OAuthVersion.OAuth20).getClientId();
    3156    }
    3257
    3358    /**
    … … class OAuthParametersTest {  
    5176        // a server JOSM knows nothing about has no client id until the user enters one
    5277        assertEquals("", OAuthParameters.createFromApiUrl(thirdParty, OAuthVersion.OAuth20).getClientId());
    5378
    54         // once the parameters are remembered - as the authentication preferences do, under the API URL - they
    55         // are found both by the API URL and by the host, which is what a connection has at hand
     79        // once the parameters are remembered - as the authentication preferences do - they are found both by the
     80        // API URL and by the host, which is what a connection has at hand
     81        OAuthParameters.setUseDefault(thirdParty, false);
    5682        new OAuth20Parameters("entered-client-id", null, thirdParty, thirdParty, "http://127.0.0.1:8111/oauth_authorization")
    5783                .rememberPreferences();
    5884        assertEquals("entered-client-id",
    … … class OAuthParametersTest {  
    6187                OAuthParameters.createFromApiUrl("https://api.openhistoricalmap.org/api", OAuthVersion.OAuth20).getApiUrl());
    6288    }
    6389
     90    /**
     91     * The parameters the user entered are stored under the host of the API, which is where the access token of the
     92     * server is stored too, and replace those stored under the API URL by earlier versions of JOSM.
     93     */
     94    @Test
     95    void testParametersAreStoredUnderTheHost() {
     96        NetworkManager.setOffline(OnlineResource.ALL);
     97        OAuthParameters.setUseDefault(THIRD_PARTY, false);
     98        // as stored by earlier versions of JOSM, which are still found
     99        Config.getPref().put("oauth.access-token.parameters.OAuth20." + THIRD_PARTY,
     100                enteredParameters(THIRD_PARTY, "old-client-id").toPreferencesString());
     101        assertEquals("old-client-id", clientIdOf(THIRD_PARTY));
     102
     103        enteredParameters(THIRD_PARTY, "new-client-id").rememberPreferences();
     104        assertNotNull(Config.getPref().get("oauth.access-token.parameters.OAuth20." + THIRD_PARTY_HOST, null));
     105        assertNull(Config.getPref().get("oauth.access-token.parameters.OAuth20." + THIRD_PARTY, null),
     106                "the parameters stored by earlier versions of JOSM are left behind");
     107        assertEquals("new-client-id", clientIdOf(THIRD_PARTY));
     108        assertEquals("new-client-id", clientIdOf(THIRD_PARTY_HOST));
     109    }
     110
     111    /**
     112     * "Use default settings" is a setting of each server: entering the client id of one server does not take the
     113     * client ids JOSM has for the other servers away, and the entered parameters are not used once the server is set
     114     * to use the default settings again, but stay for when they are needed again.
     115     */
     116    @Test
     117    void testUseDefaultIsASettingOfEachServer() {
     118        NetworkManager.setOffline(OnlineResource.ALL);
     119        assertTrue(OAuthParameters.isUseDefault(THIRD_PARTY));
     120        OAuthParameters.setUseDefault(THIRD_PARTY, false);
     121        enteredParameters(THIRD_PARTY, "entered-client-id").rememberPreferences();
     122        enteredParameters(OHM, "not-used").rememberPreferences();
     123
     124        assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY));
     125        assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY_HOST));
     126        assertTrue(OAuthParameters.isUseDefault(OHM));
     127        assertEquals("entered-client-id", clientIdOf(THIRD_PARTY));
     128        assertEquals("Hl5yIhFS-Egj6aY7A35ouLOuZl0EHjj8JJQQ46IO96E", clientIdOf(OHM));
     129
     130        OAuthParameters.setUseDefault(THIRD_PARTY, true);
     131        assertEquals("", clientIdOf(THIRD_PARTY));
     132        OAuthParameters.setUseDefault(THIRD_PARTY, false);
     133        assertEquals("entered-client-id", clientIdOf(THIRD_PARTY));
     134    }
     135
     136    /**
     137     * Until a server has a "use default settings" of its own, the setting earlier versions of JOSM had for all
     138     * servers applies, so that the parameters entered with them are still used.
     139     */
     140    @Test
     141    void testUseDefaultFallsBackToTheSettingForAllServers() {
     142        Config.getPref().putBoolean("oauth.settings.use-default", false);
     143        assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY));
     144        OAuthParameters.setUseDefault(THIRD_PARTY, true);
     145        assertTrue(OAuthParameters.isUseDefault(THIRD_PARTY));
     146        assertFalse(OAuthParameters.isUseDefault(OHM));
     147    }
     148
     149    /**
     150     * The OAuth settings of a server are stored under its host, whether it is given as the API URL or as the host,
     151     * and a missing API URL does not throw.
     152     */
     153    @Test
     154    void testGetHost() {
     155        assertEquals(THIRD_PARTY_HOST, OAuthParameters.getHost(THIRD_PARTY));
     156        assertEquals(THIRD_PARTY_HOST, OAuthParameters.getHost(THIRD_PARTY_HOST));
     157        assertEquals("localhost", OAuthParameters.getHost("http://localhost:3000/api"));
     158        assertNull(OAuthParameters.getHost(null));
     159        assertTrue(OAuthParameters.isUseDefault(null));
     160        OAuthParameters.setUseDefault(null, false);
     161        assertTrue(OAuthParameters.isUseDefault(null));
     162        // parameters without a server are not stored under a key without a host
     163        new OAuth20Parameters("a-client-id", null, "", "", "", REDIRECT_URI).rememberPreferences();
     164        assertNull(Config.getPref().get("oauth.access-token.parameters.OAuth20.", null));
     165    }
     166
     167    /**
     168     * When the server does not publish its OAuth metadata, the endpoints are those of openstreetmap-website, on the
     169     * website rather than below the API URL: {@code <api url>/authorize} is wrong for every OSM API server.
     170     */
     171    @Test
     172    void testEndpointsWithoutDiscovery() {
     173        NetworkManager.setOffline(OnlineResource.ALL);
     174        final IOAuthParameters thirdParty = OAuthParameters.createDefault(THIRD_PARTY, OAuthVersion.OAuth20);
     175        assertEquals("https://nonprod-mapops.example.org/oauth2/authorize", thirdParty.getAuthorizationUrl());
     176        assertEquals("https://nonprod-mapops.example.org/oauth2/token", thirdParty.getAccessTokenUrl());
     177        assertEquals(THIRD_PARTY, thirdParty.getApiUrl());
     178        // the default API is served from a host of its own
     179        final IOAuthParameters osm = OAuthParameters.createDefault("https://api.openstreetmap.org/api", OAuthVersion.OAuth20);
     180        assertEquals("https://www.openstreetmap.org/oauth2/authorize", osm.getAuthorizationUrl());
     181        assertEquals("https://www.openstreetmap.org/oauth2/token", osm.getAccessTokenUrl());
     182    }
     183
     184    /**
     185     * The OAuth metadata (RFC 8414) of a server is looked up on its port, such as that of a development server on
     186     * http://localhost:3000. Non-regression test: the port was dropped, so the metadata was not found.
     187     */
     188    @Test
     189    void testDiscoveryUsesThePort() {
     190        final WireMockServer server = new WireMockServer(WireMockConfiguration.options().dynamicPort());
     191        server.start();
     192        try {
     193            final String website = "http://localhost:" + server.port();
     194            server.stubFor(WireMock.get(WireMock.urlEqualTo("/.well-known/oauth-authorization-server")).willReturn(WireMock.okJson(
     195                    "{\"authorization_endpoint\": \"" + website + "/discovered/authorize\","
     196                    + " \"token_endpoint\": \"" + website + "/discovered/token\"}")));
     197            final IOAuthParameters parameters = OAuthParameters.createDefault(website + "/api", OAuthVersion.OAuth20);
     198            assertEquals(website + "/discovered/authorize", parameters.getAuthorizationUrl());
     199            assertEquals(website + "/discovered/token", parameters.getAccessTokenUrl());
     200        } finally {
     201            server.stop();
     202        }
     203    }
     204
    64205    /**
    65206     * Unit test of method {@link OAuthParameters#createDefault}.
    66207     */
  • deleted file test/unit/org/openstreetmap/josm/data/oauth/OsmPrivilegesTest.java

    diff --git test/unit/org/openstreetmap/josm/data/oauth/OsmPrivilegesTest.java test/unit/org/openstreetmap/josm/data/oauth/OsmPrivilegesTest.java
    deleted file mode 100644
    index c723338baa..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.data.oauth;
    3 
    4 import static org.junit.jupiter.api.Assertions.assertFalse;
    5 import static org.junit.jupiter.api.Assertions.assertTrue;
    6 
    7 import org.junit.jupiter.api.Test;
    8 
    9 /**
    10  * Unit tests for class {@link OsmPrivileges}.
    11  */
    12 class OsmPrivilegesTest {
    13 
    14     /**
    15      * Unit test of getters/setters.
    16      */
    17     @Test
    18     void testGettersSetters() {
    19         OsmPrivileges p = new OsmPrivileges();
    20         assertFalse(p.isAllowModifyNotes());
    21         assertFalse(p.isAllowReadGpx());
    22         assertFalse(p.isAllowReadPrefs());
    23         assertFalse(p.isAllowWriteApi());
    24         assertFalse(p.isAllowWriteGpx());
    25         assertFalse(p.isAllowWritePrefs());
    26         p.setAllowModifyNotes(true);
    27         assertTrue(p.isAllowModifyNotes());
    28         p.setAllowReadGpx(true);
    29         assertTrue(p.isAllowReadGpx());
    30         p.setAllowReadPrefs(true);
    31         assertTrue(p.isAllowReadPrefs());
    32         p.setAllowWriteApi(true);
    33         assertTrue(p.isAllowWriteApi());
    34         p.setAllowWriteGpx(true);
    35         assertTrue(p.isAllowWriteGpx());
    36         p.setAllowWritePrefs(true);
    37         assertTrue(p.isAllowWritePrefs());
    38     }
    39 }
  • test/unit/org/openstreetmap/josm/gui/ExceptionDialogUtilTest.java

    diff --git test/unit/org/openstreetmap/josm/gui/ExceptionDialogUtilTest.java test/unit/org/openstreetmap/josm/gui/ExceptionDialogUtilTest.java
    index 6f10a93c20..eff627b27a 100644
     
    11// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.gui;
    33
     4import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
     6import static org.junit.jupiter.api.Assertions.assertTrue;
     7
     8import java.util.Collections;
     9import java.util.concurrent.atomic.AtomicBoolean;
     10
    411import org.junit.jupiter.api.Test;
     12import org.openstreetmap.josm.TestUtils;
     13import org.openstreetmap.josm.actions.PreferencesAction;
     14import org.openstreetmap.josm.io.MissingOAuthAccessTokenException;
     15import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     16import org.openstreetmap.josm.testutils.mockers.HelpAwareOptionPaneMocker;
     17import org.openstreetmap.josm.tools.ExceptionUtil;
    518
     19import mockit.Mock;
     20import mockit.MockUp;
    621import net.trajano.commons.testing.UtilityClassTestUtil;
    722
    823/**
    924 * Unit tests of {@link ExceptionDialogUtil} class.
    1025 */
     26@BasicPreferences
    1127class ExceptionDialogUtilTest {
    1228    /**
    1329     * Tests that {@code ExceptionDialogUtil} satisfies utility class criteria.
    … … class ExceptionDialogUtilTest {  
    1733    void testUtilityClass() throws ReflectiveOperationException {
    1834        UtilityClassTestUtil.assertUtilityClassWellDefined(ExceptionDialogUtil.class);
    1935    }
     36
     37    /**
     38     * Without an OAuth Access Token the user is offered to open the preferences, where JOSM is authorized or the
     39     * client id or a token is entered.
     40     */
     41    @Test
     42    void testMissingOAuthAccessTokenOffersThePreferences() {
     43        assertEquals(1, explainMissingOAuthAccessToken("Open preferences"));
     44        assertEquals(0, explainMissingOAuthAccessToken("Close"));
     45    }
     46
     47    private static int explainMissingOAuthAccessToken(String answer) {
     48        TestUtils.assumeWorkingJMockit();
     49        final MissingOAuthAccessTokenException e = MissingOAuthAccessTokenException.clientIdMissing("https://example.org/api");
     50        final HelpAwareOptionPaneMocker mocker = new HelpAwareOptionPaneMocker(
     51                Collections.singletonMap(ExceptionUtil.explainMissingOAuthAccessTokenException(e), answer));
     52        final AtomicBoolean opened = new AtomicBoolean();
     53        new MockUp<PreferencesAction>() {
     54            @Mock
     55            public void run() {
     56                opened.set(true);
     57            }
     58        };
     59        ExceptionDialogUtil.explainMissingOAuthAccessTokenException(e);
     60        assertEquals(1, mocker.getInvocationLog().size());
     61        assertEquals("Authentication failed", mocker.getInvocationLog().get(0)[2]);
     62        if (opened.get()) {
     63            assertTrue(answer.startsWith("Open"));
     64            return 1;
     65        }
     66        assertFalse(answer.startsWith("Open"));
     67        return 0;
     68    }
    2069}
  • test/unit/org/openstreetmap/josm/gui/io/DownloadOpenChangesetsTaskTest.java

    diff --git test/unit/org/openstreetmap/josm/gui/io/DownloadOpenChangesetsTaskTest.java test/unit/org/openstreetmap/josm/gui/io/DownloadOpenChangesetsTaskTest.java
    index 8ce5e668b9..f4b7e43c6e 100644
    import static org.junit.jupiter.api.Assertions.assertNull;  
    77import static org.junit.jupiter.api.Assertions.assertTrue;
    88
    99import java.awt.GraphicsEnvironment;
    10 import java.net.URL;
    1110import java.util.HashMap;
    1211import java.util.Map;
    1312
    … … import javax.swing.JPanel;  
    1716import org.junit.jupiter.api.Test;
    1817import org.openstreetmap.josm.TestUtils;
    1918import org.openstreetmap.josm.data.UserIdentityManager;
    20 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    2119import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    2220import org.openstreetmap.josm.testutils.annotations.OsmApi;
    2321import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker;
    2422import org.openstreetmap.josm.testutils.mockers.WindowMocker;
    25 import org.openstreetmap.josm.tools.UserCancelException;
    26 
    27 import mockit.Invocation;
    28 import mockit.Mock;
    29 import mockit.MockUp;
    3023
    3124/**
    3225 * Unit tests of {@link DownloadOpenChangesetsTask} class.
    … … import mockit.MockUp;  
    3427@BasicPreferences
    3528@OsmApi(OsmApi.APIType.DEV)
    3629class DownloadOpenChangesetsTaskTest {
    37     /**
    38      * OAuth wizard mocker.
    39      */
    40     public static class OAuthWizardMocker extends MockUp<OAuthAuthorizationWizard> {
    41         /** {@code true} if wizard has been called */
    42         public boolean called;
    43 
    44         @Mock
    45         void showDialog() throws UserCancelException {
    46             this.called = true;
    47             throw new UserCancelException();
    48         }
    49 
    50         @Mock
    51         void obtainAccessToken(final Invocation invocation, final URL serverUrl) {
    52             if (GraphicsEnvironment.isHeadless()) {
    53                 // we can't really let execution proceed any further as construction of the ui
    54                 // elements will fail with a mocked Window
    55                 this.called = true;
    56                 return;
    57             }
    58             // else we can allow a bit more of the code to be covered before we raise
    59             // UserCancelException in showDialog
    60             invocation.proceed(serverUrl);
    61         }
    62     }
    63 
    6430    /**
    6531     * Test of {@link DownloadOpenChangesetsTask} class when anonymous.
    6632     */
  • new file test/unit/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanelTest.java

    diff --git test/unit/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanelTest.java test/unit/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanelTest.java
    new file mode 100644
    index 0000000000..dc2a6daae4
    - +  
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.gui.oauth;
     3
     4import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
     5import static org.junit.jupiter.api.Assertions.assertEquals;
     6import static org.junit.jupiter.api.Assertions.assertFalse;
     7import static org.junit.jupiter.api.Assertions.assertNotNull;
     8import static org.junit.jupiter.api.Assertions.assertTrue;
     9
     10import java.awt.Component;
     11import java.lang.reflect.Field;
     12import java.util.concurrent.ExecutionException;
     13
     14import javax.swing.JCheckBox;
     15import javax.swing.JComponent;
     16import javax.swing.JLabel;
     17import javax.swing.JTextField;
     18
     19import org.junit.jupiter.api.AfterEach;
     20import org.junit.jupiter.api.BeforeEach;
     21import org.junit.jupiter.api.Test;
     22import org.openstreetmap.josm.data.oauth.IOAuthParameters;
     23import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
     24import org.openstreetmap.josm.data.oauth.OAuthParameters;
     25import org.openstreetmap.josm.data.oauth.OAuthVersion;
     26import org.openstreetmap.josm.data.oauth.osm.OsmScopes;
     27import org.openstreetmap.josm.gui.MainApplication;
     28import org.openstreetmap.josm.gui.util.GuiHelper;
     29import org.openstreetmap.josm.gui.widgets.JosmTextField;
     30import org.openstreetmap.josm.io.NetworkManager;
     31import org.openstreetmap.josm.io.OnlineResource;
     32import org.openstreetmap.josm.spi.preferences.Config;
     33import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     34import org.openstreetmap.josm.tools.ReflectionUtils;
     35
     36/**
     37 * Unit tests of {@link AdvancedOAuthPropertiesPanel}.
     38 */
     39@BasicPreferences
     40class AdvancedOAuthPropertiesPanelTest {
     41    private static final String THIRD_PARTY = "https://nonprod-mapops.example.org/api";
     42    private static final String THIRD_PARTY_HOST = "nonprod-mapops.example.org";
     43    private static final String OHM = "https://api.openhistoricalmap.org/api";
     44    private static final String OHM_HOST = "api.openhistoricalmap.org";
     45
     46    @BeforeEach
     47    void setUp() {
     48        // the default parameters would otherwise be looked up with an RFC 8414 request
     49        NetworkManager.setOffline(OnlineResource.ALL);
     50    }
     51
     52    @AfterEach
     53    void tearDown() {
     54        NetworkManager.setOnline(OnlineResource.ALL);
     55        // the preferences are static state shared with the other tests of this class
     56        for (String host : new String[] {THIRD_PARTY_HOST, OHM_HOST}) {
     57            Config.getPref().put("oauth.access-token.parameters.OAuth20." + host, null);
     58            Config.getPref().put("oauth.settings.use-default." + host, null);
     59        }
     60    }
     61
     62    private static void waitForWorkerAndEdt() throws ExecutionException, InterruptedException {
     63        MainApplication.worker.submit(() -> { }).get();
     64        GuiHelper.runInEDTAndWait(() -> { });
     65    }
     66
     67    /**
     68     * Each server has OAuth settings of its own: the panel shows those of the server whose API URL it is given,
     69     * and saves them for that server only.
     70     * @throws ExecutionException if waiting for the worker fails
     71     * @throws InterruptedException if waiting for the worker is interrupted
     72     */
     73    @Test
     74    void testSettingsFollowTheServer() throws ExecutionException, InterruptedException {
     75        OAuthParameters.setUseDefault(THIRD_PARTY, false);
     76        new OAuth20Parameters("entered-client-id", null, THIRD_PARTY, THIRD_PARTY, "http://127.0.0.1:8111/oauth_authorization")
     77                .rememberPreferences();
     78        final String entered = Config.getPref().get("oauth.access-token.parameters.OAuth20." + THIRD_PARTY_HOST, null);
     79
     80        final AdvancedOAuthPropertiesPanel panel = new AdvancedOAuthPropertiesPanel(OAuthVersion.OAuth20);
     81        panel.initialize(THIRD_PARTY);
     82        waitForWorkerAndEdt();
     83        assertFalse(panel.isUseDefaultSettings());
     84        assertEquals("entered-client-id", panel.getEnteredClientId());
     85
     86        panel.setApiUrl(OHM);
     87        waitForWorkerAndEdt();
     88        assertTrue(panel.isUseDefaultSettings(), "the settings of the other server were kept");
     89        assertEquals("Hl5yIhFS-Egj6aY7A35ouLOuZl0EHjj8JJQQ46IO96E", panel.getEnteredClientId());
     90        panel.rememberPreferences();
     91        assertTrue(OAuthParameters.isUseDefault(OHM));
     92        assertFalse(OAuthParameters.isUseDefault(THIRD_PARTY), "saved for another server");
     93        assertEquals(entered, Config.getPref().get("oauth.access-token.parameters.OAuth20." + THIRD_PARTY_HOST, null));
     94
     95        panel.setApiUrl(THIRD_PARTY);
     96        waitForWorkerAndEdt();
     97        assertFalse(panel.isUseDefaultSettings());
     98        assertEquals("entered-client-id", panel.getEnteredClientId());
     99    }
     100
     101    /**
     102     * The OAuth parameters are shown when the user enters them, that is when the default settings are not used.
     103     * The access token is not one of them: it can be pasted whichever settings are used.
     104     * @throws ReflectiveOperationException if a field cannot be accessed
     105     * @throws ExecutionException if waiting for the worker fails
     106     * @throws InterruptedException if waiting for the worker is interrupted
     107     */
     108    @Test
     109    void testParametersAreShownWhenEntered() throws ReflectiveOperationException, ExecutionException, InterruptedException {
     110        final AdvancedOAuthPropertiesPanel panel = new AdvancedOAuthPropertiesPanel(OAuthVersion.OAuth20);
     111        panel.initialize(THIRD_PARTY);
     112        waitForWorkerAndEdt();
     113        final JComponent clientId = getField(panel, "tfClientId");
     114        final JComponent accessToken = getField(panel, "tfAccessToken");
     115        assertTrue(panel.isUseDefaultSettings());
     116        assertFalse(clientId.isVisible());
     117        assertTrue(accessToken.isVisible());
     118
     119        ((JCheckBox) getField(panel, "cbUseDefaults")).setSelected(false);
     120        assertTrue(clientId.isVisible());
     121        assertTrue(accessToken.isVisible());
     122
     123        OAuthParameters.setUseDefault(THIRD_PARTY, false);
     124        final AdvancedOAuthPropertiesPanel entered = new AdvancedOAuthPropertiesPanel(OAuthVersion.OAuth20);
     125        entered.initialize(THIRD_PARTY);
     126        assertTrue(((JComponent) getField(entered, "tfClientId")).isVisible(), "the parameters are entered for this server");
     127    }
     128
     129    /**
     130     * Each field explains what it holds, and so does its label; the client id and the access token list the
     131     * permissions JOSM needs, which the application has to be registered with.
     132     */
     133    @Test
     134    void testToolTips() {
     135        final AdvancedOAuthPropertiesPanel panel = new AdvancedOAuthPropertiesPanel(OAuthVersion.OAuth20);
     136        int labels = 0;
     137        for (Component c : panel.getComponents()) {
     138            if (c instanceof JosmTextField || c instanceof JCheckBox) {
     139                assertNotNull(((JComponent) c).getToolTipText(), c::toString);
     140            } else if (c instanceof JLabel) {
     141                final JComponent field = (JComponent) ((JLabel) c).getLabelFor();
     142                assertNotNull(field, ((JLabel) c)::getText);
     143                assertEquals(field.getToolTipText(), ((JLabel) c).getToolTipText());
     144                labels++;
     145            }
     146        }
     147        assertEquals(6, labels);
     148        for (String name : new String[] {"tfClientId", "tfAccessToken"}) {
     149            final String toolTip = assertDoesNotThrow(() -> getField(panel, name)).getToolTipText();
     150            for (OsmScopes scope : OsmScopes.getJosmScopes()) {
     151                assertTrue(toolTip.contains(scope.name()), () -> name + " does not list " + scope + ": " + toolTip);
     152            }
     153        }
     154    }
     155
     156    /**
     157     * White space copied along with the values does not become part of them. Non-regression test: a client secret
     158     * pasted with a trailing space was sent as it was, and the server refused the token request with
     159     * "invalid_client".
     160     * @throws ReflectiveOperationException if a field cannot be accessed
     161     * @throws ExecutionException if waiting for the worker fails
     162     * @throws InterruptedException if waiting for the worker is interrupted
     163     */
     164    @Test
     165    void testEnteredValuesAreTrimmed() throws ReflectiveOperationException, ExecutionException, InterruptedException {
     166        final AdvancedOAuthPropertiesPanel panel = new AdvancedOAuthPropertiesPanel(OAuthVersion.OAuth20);
     167        panel.initialize(THIRD_PARTY);
     168        waitForWorkerAndEdt();
     169        ((JCheckBox) getField(panel, "cbUseDefaults")).setSelected(false);
     170        ((JTextField) getField(panel, "tfClientId")).setText(" a-client-id\t");
     171        ((JTextField) getField(panel, "tfClientSecret")).setText("a-client-secret ");
     172        ((JTextField) getField(panel, "tfRedirectUri")).setText(" http://127.0.0.1:8111/oauth_authorization");
     173        ((JTextField) getField(panel, "tfAccessTokenURL")).setText("https://nonprod-mapops.example.org/oauth2/token\n");
     174        ((JTextField) getField(panel, "tfAuthoriseURL")).setText("  https://nonprod-mapops.example.org/oauth2/authorize");
     175
     176        final IOAuthParameters parameters = panel.getAdvancedParameters();
     177        assertEquals("a-client-id", parameters.getClientId());
     178        assertEquals("a-client-secret", parameters.getClientSecret());
     179        assertEquals("http://127.0.0.1:8111/oauth_authorization", parameters.getRedirectUri());
     180        assertEquals("https://nonprod-mapops.example.org/oauth2/token", parameters.getAccessTokenUrl());
     181        assertEquals("https://nonprod-mapops.example.org/oauth2/authorize", parameters.getAuthorizationUrl());
     182        assertEquals("a-client-id", panel.getEnteredClientId());
     183    }
     184
     185    private static JComponent getField(AdvancedOAuthPropertiesPanel panel, String name) throws ReflectiveOperationException {
     186        final Field field = AdvancedOAuthPropertiesPanel.class.getDeclaredField(name);
     187        ReflectionUtils.setObjectsAccessible(field);
     188        return (JComponent) field.get(panel);
     189    }
     190
     191    /**
     192     * Saving with "use default settings" ticked keeps the settings entered earlier, for when they are needed again.
     193     * @throws ExecutionException if waiting for the worker fails
     194     * @throws InterruptedException if waiting for the worker is interrupted
     195     */
     196    @Test
     197    void testUseDefaultKeepsTheEnteredSettings() throws ExecutionException, InterruptedException {
     198        new OAuth20Parameters("entered-client-id", null, THIRD_PARTY, THIRD_PARTY, "http://127.0.0.1:8111/oauth_authorization")
     199                .rememberPreferences();
     200        final AdvancedOAuthPropertiesPanel panel = new AdvancedOAuthPropertiesPanel(OAuthVersion.OAuth20);
     201        panel.initialize(THIRD_PARTY);
     202        waitForWorkerAndEdt();
     203        assertTrue(panel.isUseDefaultSettings());
     204        panel.rememberPreferences();
     205        waitForWorkerAndEdt();
     206
     207        OAuthParameters.setUseDefault(THIRD_PARTY, false);
     208        assertEquals("entered-client-id", OAuthParameters.createFromApiUrl(THIRD_PARTY, OAuthVersion.OAuth20).getClientId());
     209    }
     210}
  • deleted file test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUITest.java

    diff --git test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUITest.java test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUITest.java
    deleted file mode 100644
    index 4194c3e830..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
    5 
    6 import org.junit.jupiter.params.ParameterizedTest;
    7 import org.junit.jupiter.params.provider.EnumSource;
    8 import org.openstreetmap.josm.data.oauth.OAuthVersion;
    9 import org.openstreetmap.josm.gui.MainApplication;
    10 import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    11 
    12 /**
    13  * Unit tests of {@link FullyAutomaticAuthorizationUI} class.
    14  */
    15 @BasicPreferences
    16 class FullyAutomaticAuthorizationUITest {
    17     /**
    18      * Unit test of {@link FullyAutomaticAuthorizationUI#FullyAutomaticAuthorizationUI}.
    19      */
    20     @ParameterizedTest
    21     @EnumSource(OAuthVersion.class)
    22     void testFullyAutomaticAuthorizationUI(OAuthVersion version) {
    23         assertDoesNotThrow(() -> new FullyAutomaticAuthorizationUI("", MainApplication.worker, version));
    24     }
    25 }
  • deleted file test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanelTest.java

    diff --git test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanelTest.java test/unit/org/openstreetmap/josm/gui/oauth/FullyAutomaticPropertiesPanelTest.java
    deleted file mode 100644
    index 28f3489304..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.junit.jupiter.api.Assertions.assertTrue;
    5 
    6 import org.junit.jupiter.api.Test;
    7 import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    8 
    9 /**
    10  * Unit tests of {@link FullyAutomaticPropertiesPanel} class.
    11  */
    12 @BasicPreferences
    13 class FullyAutomaticPropertiesPanelTest {
    14     /**
    15      * Unit test of {@link FullyAutomaticPropertiesPanel#FullyAutomaticPropertiesPanel}.
    16      */
    17     @Test
    18     void testFullyAutomaticPropertiesPanel() {
    19         assertTrue(new FullyAutomaticPropertiesPanel().getComponentCount() > 0);
    20     }
    21 }
  • deleted file test/unit/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUITest.java

    diff --git test/unit/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUITest.java test/unit/org/openstreetmap/josm/gui/oauth/ManualAuthorizationUITest.java
    deleted file mode 100644
    index 9f702c29e8..0000000000
    + -  
    1 // License: GPL. For details, see LICENSE file.
    2 package org.openstreetmap.josm.gui.oauth;
    3 
    4 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
    5 
    6 import org.junit.jupiter.api.Test;
    7 import org.openstreetmap.josm.data.oauth.OAuthVersion;
    8 import org.openstreetmap.josm.gui.MainApplication;
    9 import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
    10 
    11 /**
    12  * Unit tests of {@link ManualAuthorizationUI} class.
    13  */
    14 @BasicPreferences
    15 class ManualAuthorizationUITest {
    16     /**
    17      * Unit test of {@link ManualAuthorizationUI#ManualAuthorizationUI}.
    18      */
    19     @Test
    20     void testManualAuthorizationUI() {
    21         assertDoesNotThrow(() -> new ManualAuthorizationUI("", MainApplication.worker, OAuthVersion.OAuth20));
    22     }
    23 }
  • new file test/unit/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanelTest.java

    diff --git test/unit/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanelTest.java test/unit/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanelTest.java
    new file mode 100644
    index 0000000000..a8b5f00969
    - +  
     1// License: GPL. For details, see LICENSE file.
     2package org.openstreetmap.josm.gui.preferences.server;
     3
     4import static org.junit.jupiter.api.Assertions.assertFalse;
     5import static org.junit.jupiter.api.Assertions.assertNull;
     6import static org.junit.jupiter.api.Assertions.assertTrue;
     7
     8import java.lang.reflect.Field;
     9
     10import javax.swing.JPanel;
     11import javax.swing.JRadioButton;
     12
     13import org.junit.jupiter.api.AfterEach;
     14import org.junit.jupiter.api.Test;
     15import org.openstreetmap.josm.actions.ExpertToggleAction;
     16import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
     17import org.openstreetmap.josm.data.oauth.OAuthVersion;
     18import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel;
     19import org.openstreetmap.josm.io.NetworkManager;
     20import org.openstreetmap.josm.io.OnlineResource;
     21import org.openstreetmap.josm.io.OsmApi;
     22import org.openstreetmap.josm.spi.preferences.Config;
     23import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     24import org.openstreetmap.josm.tools.ReflectionUtils;
     25
     26/**
     27 * Unit tests of {@link AuthenticationPreferencesPanel}.
     28 */
     29@BasicPreferences
     30class AuthenticationPreferencesPanelTest {
     31
     32    @AfterEach
     33    void tearDown() {
     34        OAuthAccessTokenHolder.getInstance().clear();
     35        ExpertToggleAction.getInstance().setExpert(false);
     36        NetworkManager.setOnline(OnlineResource.ALL);
     37        Config.getPref().put("osm-server.auth-method", null);
     38        Config.getPref().put("osm-server.url", null);
     39    }
     40
     41    private static AuthenticationPreferencesPanel createPanel(String authMethod) {
     42        // the OAuth panel looks up the default parameters of the API, which must not make a network request
     43        NetworkManager.setOffline(OnlineResource.ALL);
     44        Config.getPref().put("osm-server.auth-method", authMethod);
     45        return new AuthenticationPreferencesPanel();
     46    }
     47
     48    private static Object getField(AuthenticationPreferencesPanel panel, String name) throws ReflectiveOperationException {
     49        final Field field = AuthenticationPreferencesPanel.class.getDeclaredField(name);
     50        ReflectionUtils.setObjectsAccessible(field);
     51        return field.get(panel);
     52    }
     53
     54    private static boolean isMethodChoiceVisible(AuthenticationPreferencesPanel panel) throws ReflectiveOperationException {
     55        return ((JPanel) getField(panel, "pnlAuthenticationMethod")).isVisible();
     56    }
     57
     58    /**
     59     * Basic authentication is for experts: a normal user using OAuth 2.0 is not offered the choice.
     60     * @throws ReflectiveOperationException if a field cannot be accessed
     61     */
     62    @Test
     63    void testMethodChoiceHiddenFromNormalUsers() throws ReflectiveOperationException {
     64        ExpertToggleAction.getInstance().setExpert(false);
     65        assertFalse(isMethodChoiceVisible(createPanel("oauth20")));
     66    }
     67
     68    /**
     69     * A normal user whose profile still uses basic authentication keeps seeing the setting, so that it can be changed.
     70     * @throws ReflectiveOperationException if a field cannot be accessed
     71     */
     72    @Test
     73    void testMethodChoiceShownWhileBasicAuthenticationIsUsed() throws ReflectiveOperationException {
     74        ExpertToggleAction.getInstance().setExpert(false);
     75        final AuthenticationPreferencesPanel panel = createPanel("basic");
     76        assertTrue(((JRadioButton) getField(panel, "rbBasicAuthentication")).isSelected());
     77        assertTrue(isMethodChoiceVisible(panel));
     78    }
     79
     80    /**
     81     * Basic authentication is not offered for the servers which accept OAuth 2.0 only, even to experts, unless it
     82     * is in use already, so that it can be changed.
     83     * @throws ReflectiveOperationException if a field cannot be accessed
     84     */
     85    @Test
     86    void testNoBasicAuthenticationForOAuthOnlyServers() throws ReflectiveOperationException {
     87        ExpertToggleAction.getInstance().setExpert(true);
     88        for (String apiUrl : new String[] {Config.getUrls().getDefaultOsmApiUrl(), "https://opengeofiction.net/api",
     89                "https://opengeofiction.net/api/"}) {
     90            Config.getPref().put("osm-server.url", apiUrl);
     91            assertFalse(((JRadioButton) getField(createPanel("oauth20"), "rbBasicAuthentication")).isEnabled(), apiUrl);
     92            assertTrue(((JRadioButton) getField(createPanel("basic"), "rbBasicAuthentication")).isEnabled(),
     93                    () -> apiUrl + ": a user of basic authentication could not leave it");
     94        }
     95        Config.getPref().put("osm-server.url", "https://nonprod-mapops.example.org/api");
     96        assertTrue(((JRadioButton) getField(createPanel("oauth20"), "rbBasicAuthentication")).isEnabled());
     97    }
     98
     99    /**
     100     * Choosing the authentication method does not save what was entered in the OAuth preferences: only OK does.
     101     * <p>
     102     * Non-regression test: selecting OAuth 2.0 saved the OAuth preferences, and so an Access Token pasted but not
     103     * confirmed with OK.
     104     * @throws ReflectiveOperationException if a field cannot be accessed
     105     */
     106    @Test
     107    void testChoosingTheMethodDoesNotSaveTheToken() throws ReflectiveOperationException {
     108        final AuthenticationPreferencesPanel panel = createPanel("oauth20");
     109        final Object oauth = getField(panel, "pnlOAuth20Preferences");
     110        final Field pnlAdvancedProperties = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAdvancedProperties");
     111        ReflectionUtils.setObjectsAccessible(pnlAdvancedProperties);
     112        ((AdvancedOAuthPropertiesPanel) pnlAdvancedProperties.get(oauth)).setAccessToken("a-pasted-token");
     113
     114        ((JRadioButton) getField(panel, "rbBasicAuthentication")).setSelected(true);
     115        ((JRadioButton) getField(panel, "rbOAuth20")).setSelected(true);
     116
     117        assertNull(Config.getPref().get("oauth.access-token.object.OAuth20." + OsmApi.getOsmApi().getHost(), null),
     118                "the token was saved without OK");
     119        assertNull(OAuthAccessTokenHolder.getInstance().getAccessToken(OsmApi.getOsmApi().getServerUrl(), OAuthVersion.OAuth20));
     120    }
     121
     122    /**
     123     * The choice follows expert mode, unless basic authentication is selected.
     124     * <p>
     125     * {@link ExpertToggleAction} only keeps weak references to its listeners, so the panel has to hold on to its
     126     * own; the garbage collection makes sure the test notices if it does not.
     127     * @throws ReflectiveOperationException if a field cannot be accessed
     128     */
     129    @Test
     130    void testMethodChoiceFollowsExpertMode() throws ReflectiveOperationException {
     131        ExpertToggleAction.getInstance().setExpert(true);
     132        final AuthenticationPreferencesPanel panel = createPanel("oauth20");
     133        assertTrue(isMethodChoiceVisible(panel));
     134        System.gc();
     135
     136        ExpertToggleAction.getInstance().setExpert(false);
     137        assertFalse(isMethodChoiceVisible(panel));
     138        ExpertToggleAction.getInstance().setExpert(true);
     139        assertTrue(isMethodChoiceVisible(panel));
     140
     141        // an expert selects basic authentication, then leaves expert mode: the setting stays in sight
     142        ((JRadioButton) getField(panel, "rbBasicAuthentication")).setSelected(true);
     143        ExpertToggleAction.getInstance().setExpert(false);
     144        assertTrue(isMethodChoiceVisible(panel));
     145    }
     146}
  • test/unit/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanelTest.java

    diff --git test/unit/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanelTest.java test/unit/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanelTest.java
    index f9afe52a5d..04f5911a00 100644
    package org.openstreetmap.josm.gui.preferences.server;  
    33
    44import static org.junit.jupiter.api.Assertions.assertAll;
    55import static org.junit.jupiter.api.Assertions.assertEquals;
     6import static org.junit.jupiter.api.Assertions.assertFalse;
    67import static org.junit.jupiter.api.Assertions.assertNotNull;
    78import static org.junit.jupiter.api.Assertions.assertNull;
    89import static org.junit.jupiter.api.Assertions.assertSame;
     10import static org.junit.jupiter.api.Assertions.assertTrue;
    911import static org.junit.jupiter.api.Assertions.fail;
    1012import static org.openstreetmap.josm.tools.I18n.tr;
    1113
     14import java.awt.GraphicsEnvironment;
    1215import java.lang.reflect.Field;
    1316import java.net.Authenticator;
     17import java.net.URI;
    1418import java.util.ArrayList;
     19import java.util.Collections;
    1520import java.util.List;
     21import java.util.concurrent.CountDownLatch;
     22import java.util.concurrent.ExecutionException;
     23import java.util.stream.Stream;
    1624
    1725import javax.swing.JButton;
     26import javax.swing.JCheckBox;
     27import javax.swing.JOptionPane;
    1828import javax.swing.JPanel;
     29import javax.swing.JTextField;
    1930
    2031import org.junit.jupiter.api.AfterEach;
     32import org.junit.jupiter.api.Test;
    2133import org.junit.jupiter.params.ParameterizedTest;
    2234import org.junit.jupiter.params.provider.EnumSource;
     35import org.openstreetmap.josm.TestUtils;
    2336import org.openstreetmap.josm.data.oauth.OAuth20Exception;
    2437import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
    2538import org.openstreetmap.josm.data.oauth.OAuth20Token;
    2639import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
     40import org.openstreetmap.josm.data.oauth.OAuthParameters;
    2741import org.openstreetmap.josm.data.oauth.OAuthVersion;
     42import org.openstreetmap.josm.gui.MainApplication;
     43import org.openstreetmap.josm.gui.oauth.AdvancedOAuthPropertiesPanel;
     44import org.openstreetmap.josm.gui.util.GuiHelper;
     45import org.openstreetmap.josm.io.NetworkManager;
     46import org.openstreetmap.josm.io.OnlineResource;
    2847import org.openstreetmap.josm.io.OsmApi;
    2948import org.openstreetmap.josm.io.auth.CredentialsAgentException;
    3049import org.openstreetmap.josm.io.auth.CredentialsManager;
     50import org.openstreetmap.josm.io.remotecontrol.RemoteControl;
     51import org.openstreetmap.josm.spi.preferences.Config;
    3152import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     53import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker;
     54import org.openstreetmap.josm.testutils.mockers.OpenBrowserMocker;
     55import org.openstreetmap.josm.testutils.mockers.WindowMocker;
     56import org.openstreetmap.josm.tools.HttpClient;
    3257import org.openstreetmap.josm.tools.ReflectionUtils;
    3358
    3459/**
    … … class OAuthAuthenticationPreferencesPanelTest {  
    5580        }
    5681
    5782        assertAll(exceptionList.stream().map(e -> () -> fail(e)));
     83        // removing a token keeps the OAuth settings of the server
     84        Config.getPref().removeSensitive("oauth.access-token.parameters.OAuth20." + OsmApi.getOsmApi().getHost());
     85        Config.getPref().put("oauth.settings.use-default." + OsmApi.getOsmApi().getHost(), null);
     86        NetworkManager.setOnline(OnlineResource.ALL);
    5887    }
    5988
    6089    @ParameterizedTest
    … … class OAuthAuthenticationPreferencesPanelTest {  
    73102        panel.initFromPreferences();
    74103        assertSame(pnlAlreadyAuthorised.get(panel), holder.getComponent(0), "Authentication should now be set");
    75104        assertNotNull(getAuthorization(oAuthVersion));
    76         final JPanel buttons = (JPanel) ((JPanel) pnlAlreadyAuthorised.get(panel)).getComponent(5);
    77         final JButton action = (JButton) buttons.getComponent(2);
     105        final JButton action = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(2);
    78106        assertEquals(tr("Remove token"), action.getText(), "The selected button should be for removing the token");
    79107        action.getAction().actionPerformed(null);
    80108        panel.saveToPreferences(); // Save to preferences should make the removal permanent
    81         // Ensure that the token holder has been reset for OAuth 1.0a
     109        // Ensure that the token holder has been reset
    82110        OAuthAccessTokenHolder.getInstance().clear();
    83111        OAuthAccessTokenHolder.getInstance().init(CredentialsManager.getInstance());
    84112        assertNull(getAuthorization(oAuthVersion), "No authentication data should be stored");
    … … class OAuthAuthenticationPreferencesPanelTest {  
    86114        assertSame(pnlNotYetAuthorised.get(panel), holder.getComponent(0), "No authentication should be set");
    87115    }
    88116
     117    /**
     118     * The "New Access Token" button follows the client id entered in the advanced OAuth parameters, like the
     119     * "Authorize now" button does. Non-regression test: the buttons of the panel shown when a token exists were
     120     * looked up by component index, which pointed at the filler panel instead, so this button was never updated.
     121     * @throws ReflectiveOperationException if a field cannot be accessed
     122     * @throws CredentialsAgentException if the token cannot be stored
     123     * @throws OAuth20Exception if the token cannot be built
     124     * @throws ExecutionException if waiting for the worker fails
     125     * @throws InterruptedException if waiting for the worker is interrupted
     126     */
     127    @Test
     128    void testRenewButtonFollowsTheClientId() throws ReflectiveOperationException, CredentialsAgentException, OAuth20Exception,
     129            ExecutionException, InterruptedException {
     130        // the default parameters of the API would otherwise be looked up with an RFC 8414 request
     131        NetworkManager.setOffline(OnlineResource.ALL);
     132        try {
     133            final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     134            addAuthorization(OAuthVersion.OAuth20);
     135            panel.initFromPreferences();
     136            waitForWorkerAndEdt();
     137
     138            final Field pnlAdvancedProperties = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAdvancedProperties");
     139            final Field cbUseDefaults = AdvancedOAuthPropertiesPanel.class.getDeclaredField("cbUseDefaults");
     140            final Field tfClientId = AdvancedOAuthPropertiesPanel.class.getDeclaredField("tfClientId");
     141            ReflectionUtils.setObjectsAccessible(pnlAdvancedProperties, cbUseDefaults, tfClientId);
     142            final AdvancedOAuthPropertiesPanel advanced = (AdvancedOAuthPropertiesPanel) pnlAdvancedProperties.get(panel);
     143            ((JCheckBox) cbUseDefaults.get(advanced)).setSelected(false);
     144            final JTextField clientId = (JTextField) tfClientId.get(advanced);
     145            final JButton renew = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(0);
     146            assertEquals(tr("New Access Token"), renew.getText());
     147
     148            clientId.setText("");
     149            assertFalse(renew.isEnabled(), "without a client id there is nothing to authorize with");
     150            clientId.setText("a-client-id");
     151            assertTrue(renew.isEnabled());
     152        } finally {
     153            NetworkManager.setOnline(OnlineResource.ALL);
     154            Config.getPref().put("oauth.settings.use-default", null);
     155        }
     156    }
     157
     158    /**
     159     * Removing the token keeps the OAuth settings entered for the server, so that a new token can be obtained
     160     * without entering them again.
     161     * @throws ReflectiveOperationException if a field cannot be accessed
     162     * @throws CredentialsAgentException if the token cannot be stored
     163     * @throws OAuth20Exception if the token cannot be built
     164     * @throws ExecutionException if waiting for the worker fails
     165     * @throws InterruptedException if waiting for the worker is interrupted
     166     */
     167    @Test
     168    void testRemoveTokenKeepsTheEnteredSettings() throws ReflectiveOperationException, CredentialsAgentException, OAuth20Exception,
     169            ExecutionException, InterruptedException {
     170        // the default parameters of the API would otherwise be looked up with an RFC 8414 request
     171        NetworkManager.setOffline(OnlineResource.ALL);
     172        // the user entered the settings, and obtained a token with them
     173        OAuthParameters.setUseDefault(OsmApi.getOsmApi().getServerUrl(), false);
     174        addAuthorization(OAuthVersion.OAuth20);
     175        final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     176        panel.initFromPreferences();
     177        waitForWorkerAndEdt();
     178        ((JButton) getAlreadyAuthorisedButtons(panel).getComponent(2)).getAction().actionPerformed(null);
     179        panel.saveToPreferences();
     180        assertNull(getAuthorization(OAuthVersion.OAuth20));
     181
     182        final OAuthAuthenticationPreferencesPanel reopened = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     183        reopened.initFromPreferences();
     184        waitForWorkerAndEdt();
     185        final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(reopened);
     186        assertFalse(advanced.isUseDefaultSettings());
     187        assertEquals("fake_id", advanced.getEnteredClientId());
     188    }
     189
     190    /**
     191     * The "Authorize now" button is enabled according to the latest change of the advanced OAuth parameters.
     192     * <p>
     193     * Non-regression test: with "use default settings" ticked, the client id is looked up on the worker thread, and
     194     * the result of that lookup was applied even when the parameters had changed again in the meantime, for example
     195     * because the box was unticked and no client id entered.
     196     * @throws ReflectiveOperationException if a field cannot be accessed
     197     * @throws ExecutionException if waiting for the worker fails
     198     * @throws InterruptedException if waiting for the worker is interrupted
     199     */
     200    @Test
     201    void testAuthorizeButtonFollowsTheLatestChange() throws ReflectiveOperationException, ExecutionException, InterruptedException {
     202        NetworkManager.setOffline(OnlineResource.ALL);
     203        final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     204        panel.initFromPreferences();
     205        waitForWorkerAndEdt();
     206        final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(panel);
     207        assertTrue(advanced.isUseDefaultSettings());
     208        final Field pnlNotYetAuthorised = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlNotYetAuthorised");
     209        ReflectionUtils.setObjectsAccessible(pnlNotYetAuthorised);
     210        final JButton authorize = (JButton) ((JPanel) pnlNotYetAuthorised.get(panel)).getComponent(1);
     211        assertTrue(authorize.isEnabled(), "JOSM has a client id for the default API");
     212
     213        // hold the worker, so that the lookup made with the default settings finishes after the next change
     214        final CountDownLatch latch = new CountDownLatch(1);
     215        MainApplication.worker.execute(() -> {
     216            try {
     217                latch.await();
     218            } catch (InterruptedException e) {
     219                Thread.currentThread().interrupt();
     220            }
     221        });
     222        try {
     223            ((JTextField) getAdvancedField(advanced, "tfClientId")).setText("");
     224            ((JCheckBox) getAdvancedField(advanced, "cbUseDefaults")).setSelected(false);
     225            assertFalse(authorize.isEnabled(), "without a client id there is nothing to authorize with");
     226        } finally {
     227            latch.countDown();
     228        }
     229        waitForWorkerAndEdt();
     230        assertFalse(authorize.isEnabled(), "the lookup made with the default settings overrode a later change");
     231    }
     232
     233    /**
     234     * A pasted access token works with nothing else: here for a server JOSM has no client id for, with no client id
     235     * entered and no network. It is taken over when the preferences are saved, not before, so that cancelling them
     236     * leaves the token as it was.
     237     * @throws Exception if a field cannot be accessed, waiting for the worker fails or the request cannot be signed
     238     */
     239    @Test
     240    void testPastedTokenWorksWithNothingElse() throws Exception {
     241        NetworkManager.setOffline(OnlineResource.ALL);
     242        final String apiUrl = "https://nonprod-mapops.example.org/api";
     243        Config.getPref().put("osm-server.url", apiUrl);
     244        try {
     245            final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     246            panel.initFromPreferences();
     247            waitForWorkerAndEdt();
     248            final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(panel);
     249            assertEquals("", advanced.getEnteredClientId());
     250
     251            final JTextField tfAccessToken = (JTextField) getAdvancedField(advanced, "tfAccessToken");
     252            assertTrue(advanced.isUseDefaultSettings());
     253            assertTrue(tfAccessToken.isEnabled(), "a token can be pasted while the default settings are used");
     254            tfAccessToken.setText(" a-pasted-token\n");
     255            tfAccessToken.postActionEvent();
     256            assertNull(OAuthAccessTokenHolder.getInstance().getAccessToken(apiUrl, OAuthVersion.OAuth20),
     257                    "taken over before the preferences were saved, so cancelling them would not undo it");
     258            panel.saveToPreferences();
     259
     260            final OAuth20Token token = (OAuth20Token) getAuthorization(OAuthVersion.OAuth20);
     261            assertNotNull(token, "the token was not saved");
     262            assertEquals("a-pasted-token", token.getBearerToken());
     263            final HttpClient request = HttpClient.create(URI.create(apiUrl + "/0.6/changeset/create").toURL(), "PUT");
     264            token.sign(request);
     265            assertEquals("Bearer a-pasted-token", request.getRequestHeader("Authorization"));
     266        } finally {
     267            CredentialsManager.getInstance().storeOAuthAccessToken(OsmApi.getOsmApi().getHost(), null);
     268            Config.getPref().removeSensitive("oauth.access-token.parameters.OAuth20." + OsmApi.getOsmApi().getHost());
     269            Config.getPref().put("osm-server.url", null);
     270        }
     271    }
     272
     273    /**
     274     * A token which the user did not change is kept as it is, rather than replaced by a token built from its text:
     275     * that would lose everything else the token holds, such as its parameters.
     276     * @throws CredentialsAgentException if the token cannot be stored
     277     * @throws OAuth20Exception if the token cannot be built
     278     * @throws ExecutionException if waiting for the worker fails
     279     * @throws InterruptedException if waiting for the worker is interrupted
     280     * @throws ReflectiveOperationException if a field cannot be accessed
     281     */
     282    @Test
     283    void testUnchangedTokenIsKept() throws CredentialsAgentException, OAuth20Exception, ExecutionException, InterruptedException,
     284            ReflectiveOperationException {
     285        NetworkManager.setOffline(OnlineResource.ALL);
     286        addAuthorization(OAuthVersion.OAuth20);
     287        final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     288        panel.initFromPreferences();
     289        waitForWorkerAndEdt();
     290        assertEquals("fake_token", getAdvancedProperties(panel).getAccessToken());
     291        panel.saveToPreferences();
     292
     293        final OAuth20Token token = (OAuth20Token) getAuthorization(OAuthVersion.OAuth20);
     294        assertEquals("fake_token", token.getBearerToken());
     295        assertEquals("fake_id", token.getParameters().getClientId());
     296    }
     297
     298    /**
     299     * Clearing the access token removes it, like the "Remove token" button does.
     300     * @throws CredentialsAgentException if the token cannot be stored
     301     * @throws OAuth20Exception if the token cannot be built
     302     * @throws ExecutionException if waiting for the worker fails
     303     * @throws InterruptedException if waiting for the worker is interrupted
     304     * @throws ReflectiveOperationException if a field cannot be accessed
     305     */
     306    @Test
     307    void testClearedTokenIsRemoved() throws CredentialsAgentException, OAuth20Exception, ExecutionException, InterruptedException,
     308            ReflectiveOperationException {
     309        NetworkManager.setOffline(OnlineResource.ALL);
     310        addAuthorization(OAuthVersion.OAuth20);
     311        final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     312        panel.initFromPreferences();
     313        waitForWorkerAndEdt();
     314        getAdvancedProperties(panel).setAccessToken("");
     315        assertNotNull(OAuthAccessTokenHolder.getInstance().getAccessToken(OsmApi.getOsmApi().getServerUrl(), OAuthVersion.OAuth20),
     316                "removed before the preferences were saved, so cancelling them would not undo it");
     317        panel.saveToPreferences();
     318        assertNull(getAuthorization(OAuthVersion.OAuth20));
     319    }
     320
     321    /**
     322     * "Test Access Token" tests the token in the field: with the field cleared there is none to test, rather than
     323     * the stored token, which the user is about to remove.
     324     * @throws Exception if a field cannot be accessed, the token cannot be stored or waiting for the worker fails
     325     */
     326    @Test
     327    void testNothingToTestWhenTheTokenIsCleared() throws Exception {
     328        TestUtils.assumeWorkingJMockit();
     329        if (GraphicsEnvironment.isHeadless()) {
     330            new WindowMocker();
     331        }
     332        final JOptionPaneSimpleMocker mocker = new JOptionPaneSimpleMocker(Collections.singletonMap(
     333                "There is no Access Token to test.", JOptionPane.OK_OPTION));
     334        NetworkManager.setOffline(OnlineResource.ALL);
     335        addAuthorization(OAuthVersion.OAuth20);
     336        final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     337        panel.initFromPreferences();
     338        waitForWorkerAndEdt();
     339        getAdvancedProperties(panel).setAccessToken("");
     340        final JButton test = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(1);
     341        assertEquals(tr("Test Access Token"), test.getText());
     342
     343        test.doClick();
     344        assertEquals(1, mocker.getInvocationLog().size(), "the stored token was tested instead");
     345    }
     346
     347    /**
     348     * "Authorize now" authorizes JOSM in the web browser straight away, with the OAuth parameters shown in the panel.
     349     * @throws Exception if a field cannot be accessed or waiting for the worker fails
     350     */
     351    @Test
     352    void testAuthorizeNowUsesTheDisplayedParameters() throws Exception {
     353        TestUtils.assumeWorkingJMockit();
     354        new OpenBrowserMocker();
     355        OpenBrowserMocker.getCalledURIs().clear();
     356        NetworkManager.setOffline(OnlineResource.ALL);
     357        RemoteControl.stop();
     358        try {
     359            final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     360            panel.initFromPreferences();
     361            waitForWorkerAndEdt();
     362            final AdvancedOAuthPropertiesPanel advanced = getAdvancedProperties(panel);
     363            advanced.setAdvancedParameters(new OAuth20Parameters("an-entered-client-id", null, "https://example.org/oauth2/token",
     364                    "https://example.org/oauth2/authorize", OsmApi.getOsmApi().getServerUrl(), "http://127.0.0.1:8111/oauth_authorization"));
     365            assertFalse(advanced.isUseDefaultSettings());
     366            final Field pnlNotYetAuthorised = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlNotYetAuthorised");
     367            ReflectionUtils.setObjectsAccessible(pnlNotYetAuthorised);
     368            final JButton authorize = (JButton) ((JPanel) pnlNotYetAuthorised.get(panel)).getComponent(1);
     369            assertEquals(tr("Authorize now"), authorize.getText());
     370
     371            authorize.doClick();
     372            GuiHelper.runInEDTAndWait(() -> { });
     373
     374            assertEquals(1, OpenBrowserMocker.getCalledURIs().size());
     375            final String url = OpenBrowserMocker.getCalledURIs().get(0).toString();
     376            assertTrue(url.startsWith("https://example.org/oauth2/authorize?"), url);
     377            assertTrue(url.contains("client_id=an-entered-client-id"), url);
     378        } finally {
     379            RemoteControl.stop();
     380        }
     381    }
     382
     383    /**
     384     * A failed attempt at a new Access Token leaves the token JOSM has as it is.
     385     * <p>
     386     * Non-regression test: the token was replaced by none whenever the authorization failed, for example when the
     387     * server refused to exchange the code for a token, so a failed renewal lost a working token.
     388     * @throws Exception if a field cannot be accessed, the token cannot be stored or the redirect cannot be sent
     389     */
     390    @Test
     391    void testFailedRenewalKeepsTheToken() throws Exception {
     392        TestUtils.assumeWorkingJMockit();
     393        new OpenBrowserMocker();
     394        OpenBrowserMocker.getCalledURIs().clear();
     395        new JOptionPaneSimpleMocker(Collections.singletonMap(
     396                "Authentication failed, please check browser for details.", JOptionPane.OK_OPTION));
     397        NetworkManager.setOffline(OnlineResource.ALL);
     398        RemoteControl.stop();
     399        addAuthorization(OAuthVersion.OAuth20);
     400        try {
     401            final OAuthAuthenticationPreferencesPanel panel = new OAuthAuthenticationPreferencesPanel(OAuthVersion.OAuth20);
     402            panel.initFromPreferences();
     403            waitForWorkerAndEdt();
     404            // the token request goes to a port nothing listens on, so that the exchange fails
     405            getAdvancedProperties(panel).setAdvancedParameters(new OAuth20Parameters("an-entered-client-id", null,
     406                    "http://127.0.0.1:1/oauth2/token", "https://example.org/oauth2/authorize",
     407                    OsmApi.getOsmApi().getServerUrl(), "http://127.0.0.1:8111/oauth_authorization"));
     408            final JButton renew = (JButton) getAlreadyAuthorisedButtons(panel).getComponent(0);
     409            assertEquals(tr("New Access Token"), renew.getText());
     410
     411            renew.doClick();
     412            GuiHelper.runInEDTAndWait(() -> { });
     413            assertEquals(1, OpenBrowserMocker.getCalledURIs().size());
     414            final String state = Stream.of(OpenBrowserMocker.getCalledURIs().get(0).getQuery().split("&"))
     415                    .filter(p -> p.startsWith("state=")).map(p -> p.substring("state=".length())).findFirst().orElseThrow();
     416            // the web browser is redirected to JOSM with a code
     417            final HttpClient redirect = HttpClient.create(
     418                    URI.create("http://127.0.0.1:8111/oauth_authorization?code=a-code&state=" + state).toURL());
     419            try {
     420                redirect.connect();
     421            } finally {
     422                redirect.disconnect();
     423            }
     424            GuiHelper.runInEDTAndWait(() -> { });
     425
     426            final OAuth20Token token = (OAuth20Token) getAuthorization(OAuthVersion.OAuth20);
     427            assertNotNull(token, "the token was lost");
     428            assertEquals("fake_token", token.getBearerToken());
     429        } finally {
     430            RemoteControl.stop();
     431        }
     432    }
     433
     434    private static AdvancedOAuthPropertiesPanel getAdvancedProperties(OAuthAuthenticationPreferencesPanel panel)
     435            throws ReflectiveOperationException {
     436        final Field pnlAdvancedProperties = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAdvancedProperties");
     437        ReflectionUtils.setObjectsAccessible(pnlAdvancedProperties);
     438        return (AdvancedOAuthPropertiesPanel) pnlAdvancedProperties.get(panel);
     439    }
     440
     441    private static Object getAdvancedField(AdvancedOAuthPropertiesPanel advanced, String name) throws ReflectiveOperationException {
     442        final Field field = AdvancedOAuthPropertiesPanel.class.getDeclaredField(name);
     443        ReflectionUtils.setObjectsAccessible(field);
     444        return field.get(advanced);
     445    }
     446
     447    /**
     448     * Waits until the panel has settled. The advanced parameters fill themselves in from the worker, then the EDT,
     449     * and setting them re-evaluates the "Authorize now" buttons, which queues more work on the worker that again
     450     * finishes on the EDT; so this goes round twice.
     451     * @throws ExecutionException if waiting for the worker fails
     452     * @throws InterruptedException if waiting for the worker is interrupted
     453     */
     454    private static void waitForWorkerAndEdt() throws ExecutionException, InterruptedException {
     455        for (int i = 0; i < 2; i++) {
     456            MainApplication.worker.submit(() -> { }).get();
     457            GuiHelper.runInEDTAndWait(() -> { });
     458        }
     459    }
     460
     461    private static JPanel getAlreadyAuthorisedButtons(OAuthAuthenticationPreferencesPanel panel) throws ReflectiveOperationException {
     462        final Field pnlAlreadyAuthorised = OAuthAuthenticationPreferencesPanel.class.getDeclaredField("pnlAlreadyAuthorised");
     463        ReflectionUtils.setObjectsAccessible(pnlAlreadyAuthorised);
     464        final Object alreadyAuthorised = pnlAlreadyAuthorised.get(panel);
     465        final Field pnlButtons = alreadyAuthorised.getClass().getDeclaredField("pnlButtons");
     466        ReflectionUtils.setObjectsAccessible(pnlButtons);
     467        return (JPanel) pnlButtons.get(alreadyAuthorised);
     468    }
     469
    89470    /**
    90471     * Add authorization preferences for the specified oauth version
    91472     * @param oAuthVersion The oauth version to use
  • test/unit/org/openstreetmap/josm/io/OsmConnectionTest.java

    diff --git test/unit/org/openstreetmap/josm/io/OsmConnectionTest.java test/unit/org/openstreetmap/josm/io/OsmConnectionTest.java
    index c9605090c9..8aaad2164d 100644
     
    22package org.openstreetmap.josm.io;
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertFalse;
    56import static org.junit.jupiter.api.Assertions.assertNotNull;
    67import static org.junit.jupiter.api.Assertions.assertNull;
    78import static org.junit.jupiter.api.Assertions.assertThrows;
    89import static org.junit.jupiter.api.Assertions.assertTrue;
    910
     11import java.awt.GraphicsEnvironment;
    1012import java.net.MalformedURLException;
    1113import java.net.URI;
     14import java.util.Collections;
    1215
    1316import javax.swing.JOptionPane;
    1417
    1518import org.junit.jupiter.api.AfterEach;
    1619import org.junit.jupiter.api.BeforeEach;
    1720import org.junit.jupiter.api.Test;
     21import org.openstreetmap.josm.TestUtils;
    1822import org.openstreetmap.josm.data.oauth.IOAuthParameters;
    1923import org.openstreetmap.josm.data.oauth.OAuth20Exception;
    2024import org.openstreetmap.josm.data.oauth.OAuth20Parameters;
    2125import org.openstreetmap.josm.data.oauth.OAuth20Token;
    2226import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
     27import org.openstreetmap.josm.data.oauth.OAuthParameters;
    2328import org.openstreetmap.josm.data.oauth.OAuthVersion;
    2429import org.openstreetmap.josm.spi.preferences.Config;
    2530import org.openstreetmap.josm.testutils.annotations.BasicPreferences;
     31import org.openstreetmap.josm.testutils.mockers.JOptionPaneSimpleMocker;
     32import org.openstreetmap.josm.testutils.mockers.WindowMocker;
    2633import org.openstreetmap.josm.tools.HttpClient;
    2734
    2835/**
    … … class OsmConnectionTest {  
    5461        NetworkManager.setOnline(OnlineResource.ALL);
    5562        OAuthAccessTokenHolder.getInstance().clear();
    5663        // preferences and the token holder are static state shared with the other tests of this class
    57         Config.getPref().put("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + API_URL, null);
     64        Config.getPref().put("oauth.access-token.parameters." + OAuthVersion.OAuth20 + "." + URI.create(API_URL).getHost(), null);
     65        Config.getPref().put("oauth.settings.use-default." + URI.create(API_URL).getHost(), null);
    5866        Config.getPref().put("osm-server.url", null);
    5967    }
    6068
    … … class OsmConnectionTest {  
    6371    }
    6472
    6573    /**
    66      * Stores the advanced OAuth parameters the way the authentication preferences do, that is under the API URL.
     74     * Stores the advanced OAuth parameters the way the authentication preferences do.
    6775     */
    6876    private static OAuth20Parameters rememberParameters() {
    6977        final OAuth20Parameters parameters = new OAuth20Parameters(CLIENT_ID, null, API_URL, API_URL, REDIRECT_URI);
     78        OAuthParameters.setUseDefault(API_URL, false);
    7079        parameters.rememberPreferences();
    7180        return parameters;
    7281    }
    … … class OsmConnectionTest {  
    114123        final MissingOAuthAccessTokenException thrown = assertThrows(MissingOAuthAccessTokenException.class,
    115124                () -> new TestConnection().addOAuth20AuthorizationHeader(client));
    116125        assertNotNull(thrown.getMessage(), "gave up only after asking the user, rather than for the missing client id");
     126        assertTrue(thrown.isClientIdMissing(), "the user is not told what is missing");
    117127        assertTrue(thrown.getMessage().contains(API_URL), thrown.getMessage());
    118128        assertNull(client.getRequestHeader("Authorization"));
    119129    }
    120130
     131    /**
     132     * A token is obtained for the API, so for a request to another host JOSM does not ask the user to authorize it,
     133     * which would not give a token for that request anyway.
     134     * @throws MalformedURLException never
     135     */
     136    @Test
     137    void testNoAuthorizationForAnotherHost() throws MalformedURLException {
     138        TestUtils.assumeWorkingJMockit();
     139        if (GraphicsEnvironment.isHeadless()) {
     140            new WindowMocker();
     141        }
     142        final JOptionPaneSimpleMocker mocker = new JOptionPaneSimpleMocker(
     143                Collections.singletonMap("Obtain OAuth 2.0 token for authentication?", JOptionPane.NO_OPTION));
     144        rememberParameters();
     145
     146        final HttpClient client = HttpClient.create(URI.create("https://elsewhere.example.org/api/0.6/user/details").toURL());
     147        final MissingOAuthAccessTokenException thrown = assertThrows(MissingOAuthAccessTokenException.class,
     148                () -> new TestConnection().addOAuth20AuthorizationHeader(client));
     149        assertFalse(thrown.isClientIdMissing());
     150        assertEquals(0, mocker.getInvocationLog().size(), "asked to obtain a token for another host");
     151    }
     152
     153    /**
     154     * A token pasted by the user signs the connection with nothing else: no client id, no endpoints, no network.
     155     * @throws Exception if the connection cannot be signed
     156     */
     157    @Test
     158    void testPastedTokenSignsTheConnection() throws Exception {
     159        OAuthAccessTokenHolder.getInstance().setAccessToken(API_URL,
     160                OAuth20Token.fromAccessToken(new OAuth20Parameters("", null, "", "", API_URL, ""), "a-pasted-token"));
     161
     162        final HttpClient client = apiRequest();
     163        new TestConnection().addOAuth20AuthorizationHeader(client);
     164        assertEquals("Bearer a-pasted-token", client.getRequestHeader("Authorization"));
     165    }
     166
    121167    /**
    122168     * An existing token is used without the parameters having to be stored, since the token carries its own.
    123169     * @throws OAuth20Exception if the token cannot be built
  • test/unit/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgentTest.java

    diff --git test/unit/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgentTest.java test/unit/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgentTest.java
    index ef32f68bed..1e93d4d81c 100644
     
    11// License: GPL. For details, see LICENSE file.
    22package org.openstreetmap.josm.io.auth;
    33
     4import static org.junit.jupiter.api.Assertions.assertEquals;
    45import static org.junit.jupiter.api.Assertions.assertFalse;
    56import static org.junit.jupiter.api.Assertions.assertNotNull;
    67import static org.junit.jupiter.api.Assertions.assertNull;
    … … class JosmPreferencesCredentialAgentTest implements CredentialsAgentTest<JosmPre  
    2526    }
    2627
    2728    /**
    28      * Removing an OAuth token removes it from the preferences, not only the parameters stored with it.
     29     * Removing an OAuth token removes it from the preferences, and keeps the parameters stored with it: they are the
     30     * OAuth settings of the server too, which are needed to obtain the next token.
    2931     * <p>
    30      * Non-regression test: both keys were built with the {@code parameters} prefix, so the token itself stayed in the
    31      * preferences in clear text. {@link CredentialsAgentTest#testLookupAndStoreOAuthTokens} did not notice, because a
    32      * lookup needs both keys and so already fails once the parameters are gone.
     32     * Non-regression test for #24932: both keys were built with the {@code parameters} prefix, so the token itself
     33     * stayed in the preferences in clear text. {@link CredentialsAgentTest#testLookupAndStoreOAuthTokens} did not
     34     * notice, because a lookup needs both keys and so already failed once the parameters were gone.
    3335     * @throws CredentialsAgentException if the token cannot be stored or removed
    3436     * @throws OAuth20Exception if the token cannot be built
    3537     */
    … … class JosmPreferencesCredentialAgentTest implements CredentialsAgentTest<JosmPre  
    4446                "https://example.org/api", "https://example.org/api", "http://127.0.0.1:8111/oauth_authorization"),
    4547                "{\"access_token\": \"a-secret-token\", \"token_type\": \"bearer\"}"));
    4648        assertNotNull(Config.getPref().get(tokenKey, null));
    47         assertNotNull(Config.getPref().get(parametersKey, null));
     49        final String parameters = Config.getPref().get(parametersKey, null);
     50        assertNotNull(parameters);
    4851
    4952        agent.storeOAuthAccessToken(host, null);
    5053
    5154        assertNull(Config.getPref().get(tokenKey, null), "the token is still stored in the preferences");
    52         assertNull(Config.getPref().get(parametersKey, null));
    5355        assertFalse(Config.getPref().getSensitive().contains(tokenKey));
    54         assertFalse(Config.getPref().getSensitive().contains(parametersKey));
     56        assertNull(agent.lookupOAuthAccessToken(host));
     57        assertEquals(parameters, Config.getPref().get(parametersKey, null), "the OAuth settings of the server are gone");
     58        Config.getPref().removeSensitive(parametersKey);
    5559    }
    5660}
  • test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java

    diff --git test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java test/unit/org/openstreetmap/josm/testutils/JOSMTestRules.java
    index f33894ff38..4faa2ca408 100644
    import org.openstreetmap.josm.data.preferences.JosmUrls;  
    5050import org.openstreetmap.josm.data.projection.ProjectionRegistry;
    5151import org.openstreetmap.josm.data.projection.Projections;
    5252import org.openstreetmap.josm.gui.MainApplication;
    53 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    5453import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreferenceTestIT;
    5554import org.openstreetmap.josm.gui.util.GuiHelper;
    5655import org.openstreetmap.josm.io.OsmApi;
    5756import org.openstreetmap.josm.io.OsmApiInitializationException;
    58 import org.openstreetmap.josm.io.OsmConnection;
    5957import org.openstreetmap.josm.io.OsmTransferCanceledException;
    6058import org.openstreetmap.josm.spi.preferences.Config;
    6159import org.openstreetmap.josm.spi.preferences.Setting;
    … … public class JOSMTestRules implements TestRule, AfterEachCallback, BeforeEachCal  
    549547        User.clearUserMap();
    550548        // Setup callbacks
    551549        DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
    552         OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
    553550        HttpClient.setFactory(Http1Client::new);
    554551
    555552        // Set up i18n
  • test/unit/org/openstreetmap/josm/testutils/annotations/JosmDefaults.java

    diff --git test/unit/org/openstreetmap/josm/testutils/annotations/JosmDefaults.java test/unit/org/openstreetmap/josm/testutils/annotations/JosmDefaults.java
    index 4146eb450f..3a2d927675 100644
    import org.openstreetmap.josm.command.DeleteCommand;  
    2020import org.openstreetmap.josm.data.Preferences;
    2121import org.openstreetmap.josm.data.UserIdentityManager;
    2222import org.openstreetmap.josm.data.osm.User;
    23 import org.openstreetmap.josm.gui.oauth.OAuthAuthorizationWizard;
    2423import org.openstreetmap.josm.gui.util.GuiHelper;
    25 import org.openstreetmap.josm.io.OsmConnection;
    2624import org.openstreetmap.josm.testutils.JOSMTestRules;
    2725import org.openstreetmap.josm.tools.Logging;
    2826import org.openstreetmap.josm.tools.MemoryManagerTest;
    … … public @interface JosmDefaults {  
    5957            User.clearUserMap();
    6058            // Setup callbacks
    6159            DeleteCommand.setDeletionCallback(DeleteAction.defaultDeletionCallback);
    62             OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
    6360        }
    6461
    6562        @Override
  • test/unit/org/openstreetmap/josm/tools/ExceptionUtilTest.java

    diff --git test/unit/org/openstreetmap/josm/tools/ExceptionUtilTest.java test/unit/org/openstreetmap/josm/tools/ExceptionUtilTest.java
    index c5178d3863..3c99473224 100644
     
    22package org.openstreetmap.josm.tools;
    33
    44import static org.junit.jupiter.api.Assertions.assertEquals;
     5import static org.junit.jupiter.api.Assertions.assertTrue;
    56
    67import java.io.IOException;
    78import java.net.HttpURLConnection;
    … … class ExceptionUtilTest {  
    277278                ExceptionUtil.explainMissingOAuthAccessTokenException(new MissingOAuthAccessTokenException()));
    278279    }
    279280
     281    /**
     282     * Without a client id, JOSM cannot obtain a token, and says so rather than to generate one.
     283     */
     284    @Test
     285    void testExplainMissingOAuthClientId() {
     286        // the server JOSM gave up on, whichever is configured by the time this is explained
     287        final String explanation = ExceptionUtil.explainMissingOAuthAccessTokenException(
     288                MissingOAuthAccessTokenException.clientIdMissing("https://other.example.org/api"));
     289        assertTrue(explanation.contains("'https://other.example.org/api'"), explanation);
     290        assertTrue(explanation.contains("because it has no OAuth Client ID for it"), explanation);
     291    }
     292
    280293    /**
    281294     * Test of {@link ExceptionUtil#explainNestedIllegalDataException} method.
    282295     */