Changeset 19707 in josm for trunk/src


Ignore:
Timestamp:
2026-11-26T22:24:37+01:00 (90 minutes ago)
Author:
stoecker
Message:

see #24928 - patch by wangi - Cleanup OAuth

Location:
trunk/src/org/openstreetmap/josm
Files:
9 deleted
16 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/org/openstreetmap/josm/data/Preferences.java

    r19536 r19707  
    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
  • trunk/src/org/openstreetmap/josm/data/UserIdentityManager.java

    r19080 r19707  
    8686    private String userName;
    8787    private UserInfo userInfo;
    88     private boolean accessTokenKeyChanged;
    89     private boolean accessTokenSecretChanged;
    9088
    9189    private UserIdentityManager() {
    … …  
    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        }
  • trunk/src/org/openstreetmap/josm/data/oauth/OAuth20Parameters.java

    r19519 r19707  
    1616
    1717import org.openstreetmap.josm.spi.preferences.Config;
     18import org.openstreetmap.josm.tools.Logging;
     19import org.openstreetmap.josm.tools.Utils;
    1820
    1921/**
    … …  
    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
  • trunk/src/org/openstreetmap/josm/data/oauth/OAuth20Token.java

    r19519 r19707  
    5050    public OAuth20Token(IOAuthParameters oauthParameters, String json) throws OAuth20Exception {
    5151        this(oauthParameters, new InputStreamReader(new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));
     52    }
     53
     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 19707
     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        }
    5273    }
    5374
  • trunk/src/org/openstreetmap/josm/data/oauth/OAuthParameters.java

    r19651 r19707  
    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() {
    … …  
    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
    … …  
    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 19707
     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 19707
     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 19707
     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 19707
     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();
    … …  
    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) {
    … …  
    181245                clientSecret = null;
    182246        }
    183         baseUrl = apiUrl;
    184247        // Check if the server is RFC 8414 compliant
    185248        try {
    … …  
    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
    … …  
    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.
    … …  
    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();
    … …  
    260331                    Logging.trace(e);
    261332                }
    262                 IOAuthParameters remembered = createFromPreferences(originalApiUrl, apiUrl);
    263                 if (remembered != null) {
    264                     return remembered;
    265                 }
    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);
     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                    }
     339                }
     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);
  • trunk/src/org/openstreetmap/josm/data/oauth/osm/OsmScopes.java

    r19519 r19707  
    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 19707
     30     */
     31    public static OsmScopes[] getJosmScopes() {
     32        return new OsmScopes[] {read_gpx, write_gpx, read_prefs, write_prefs, write_api, write_notes};
     33    }
    2434}
  • trunk/src/org/openstreetmap/josm/gui/ExceptionDialogUtil.java

    r19216 r19707  
    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;
    … …  
    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;
    … …  
    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
  • trunk/src/org/openstreetmap/josm/gui/MainApplication.java

    r19264 r19707  
    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;
    … …  
    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;
    … …  
    11111109    static void setupCallbacks() {
    11121110        HttpClient.setFactory(Http1Client::new);
    1113         OsmConnection.setOAuthAccessTokenFetcher(OAuthAuthorizationWizard::obtainAccessToken);
    11141111        AbstractCredentialsAgent.setCredentialsProvider(CredentialDialog::promptCredentials);
    11151112        MessageNotifier.setNotifierCallback(MainApplication::notifyNewMessages);
  • trunk/src/org/openstreetmap/josm/gui/oauth/AdvancedOAuthPropertiesPanel.java

    r19627 r19707  
    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;
    … …  
    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;
    … …  
    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;
    … …  
    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 *
    … …  
    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;
    … …  
    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);
    95 
    96         gc.gridx = 1;
    97         gc.weightx = 1.0;
    98         add(tfConsumerKey, gc);
    99         SelectAllOnFocusGainedDecorator.decorate(tfConsumerKey);
    100 
    101         // -- consumer secret
     99        add(label(tr("Client ID:"), tfClientId), gc);
     100
     101        gc.gridx = 1;
     102        gc.weightx = 1.0;
     103        add(tfClientId, gc);
     104        SelectAllOnFocusGainedDecorator.decorate(tfClientId);
     105
     106        // -- client secret
    102107        gc.gridy++;
    103108        gc.gridx = 0;
    104109        gc.weightx = 0.0;
    105         add(new JLabel(tr("Client Secret:")), gc);
    106 
    107         gc.gridx = 1;
    108         gc.weightx = 1.0;
    109         add(tfConsumerSecret, gc);
    110         SelectAllOnFocusGainedDecorator.decorate(tfConsumerSecret);
    111 
    112         // -- request token URL
     110        add(label(tr("Client Secret:"), tfClientSecret), gc);
     111
     112        gc.gridx = 1;
     113        gc.weightx = 1.0;
     114        add(tfClientSecret, gc);
     115        SelectAllOnFocusGainedDecorator.decorate(tfClientSecret);
     116
     117        // -- redirect URI
    113118        gc.gridy++;
    114119        gc.gridx = 0;
    115120        gc.weightx = 0.0;
    116         add(new JLabel(tr("Redirect URL:")), gc);
    117 
    118         gc.gridx = 1;
    119         gc.weightx = 1.0;
    120         add(tfRequestTokenURL, gc);
    121         SelectAllOnFocusGainedDecorator.decorate(tfRequestTokenURL);
     121        add(label(tr("Redirect URL:"), tfRedirectUri), gc);
     122
     123        gc.gridx = 1;
     124        gc.weightx = 1.0;
     125        add(tfRedirectUri, gc);
     126        SelectAllOnFocusGainedDecorator.decorate(tfRedirectUri);
    122127
    123128        // -- access token URL
    … …  
    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;
    … …  
    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;
    … …  
    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) {
    … …  
    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);
     231    }
     232
     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 19707
     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 19707
     246     */
     247    public void setAccessToken(String accessToken) {
     248        tfAccessToken.setText(accessToken);
    169249    }
    170250
    … …  
    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    }
    … …  
    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 19707
     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);
    250             }
    251         }
     338                c.setVisible(visible);
     339            }
     340        }
     341        revalidate();
    252342    }
    253343
    … …  
    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 19707
     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    }
    … …  
    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        }
    … …  
    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) {
    … …  
    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            }
    … …  
    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        }
    … …  
    345454                break;
    346455            case ItemEvent.DESELECTED:
    347                 setChildComponentsEnabled(true);
     456                setChildComponentsVisible(true);
    348457                break;
    349458            default: // Do nothing
    … …  
    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()) {
  • trunk/src/org/openstreetmap/josm/gui/oauth/package-info.java

    r8624 r19707  
    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;
  • trunk/src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java

    r19095 r19707  
    1818import javax.swing.JRadioButton;
    1919
     20import org.openstreetmap.josm.actions.ExpertToggleAction;
    2021import org.openstreetmap.josm.data.UserIdentityManager;
    2122import org.openstreetmap.josm.data.oauth.OAuthAccessTokenHolder;
    … …  
    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();
    … …  
    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"));
    … …  
    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();
    … …  
    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
    … …  
    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);
    … …  
    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();
    … …  
    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
  • trunk/src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java

    r19627 r19707  
    1313import java.awt.Insets;
    1414import java.awt.event.ActionEvent;
    15 import java.awt.event.ItemEvent;
    1615import java.beans.PropertyChangeEvent;
    1716import java.beans.PropertyChangeListener;
    … …  
    1918import java.net.URISyntaxException;
    2019import java.util.Arrays;
    21 import java.util.Objects;
    2220
    2321import javax.swing.AbstractAction;
    … …  
    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());
    … …  
    9488        cbUseForAllRequests.setToolTipText(tr("For user-based bandwidth limit instead of IP-based one"));
    9589        pnl.add(cbUseForAllRequests, GBC.eol().fill(GBC.HORIZONTAL));
    96 
    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         );
    10290
    10391        pnl.add(pnlAdvancedProperties, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 3, 0, 0));
    … …  
    10997                )
    11098        );
    111         pnlAdvancedProperties.setVisible(false);
    11299        pnlAdvancedProperties.addPropertyChangeListener(this);
    113100        return pnl;
    … …  
    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) {
    … …  
    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);
    … …  
    157145
    158146    /**
     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
     189    /**
    159190     * Sets the URL of the OSM API for which this panel is currently displaying OAuth properties.
    160191     *
    … …  
    180211     */
    181212    public void saveToPreferences() {
     213        applyEnteredAccessToken();
    182214        OAuthAccessTokenHolder.getInstance().setSaveToPreferences(cbSaveToPreferences.isSelected());
    183215        OAuthAccessTokenHolder.getInstance().save(CredentialsManager.getInstance());
    … …  
    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
    … …  
    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        /**
    … …  
    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;
    250             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;
    269279            gc.gridx = 0;
    270280            gc.gridwidth = 2;
    … …  
    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;
    … …  
    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        }
    … …  
    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()));
    … …  
    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                }
    … …  
    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    }
    … …  
    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 {
    … …  
    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    }
    … …  
    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,
    … …  
    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    }
  • trunk/src/org/openstreetmap/josm/io/MissingOAuthAccessTokenException.java

    r12470 r19707  
    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}.
    … …  
    1215    public MissingOAuthAccessTokenException() {
    1316        super();
     17        this.clientIdMissingFor = null;
    1418    }
    1519
    … …  
    2226    public MissingOAuthAccessTokenException(String message, Throwable cause) {
    2327        super(message, cause);
     28        this.clientIdMissingFor = null;
    2429    }
    2530
    … …  
    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
    … …  
    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 19707
     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 19707
     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 19707
     79     */
     80    public String getClientIdMissingFor() {
     81        return clientIdMissingFor;
    4182    }
    4283}
  • trunk/src/org/openstreetmap/josm/io/OsmConnection.java

    r19638 r19707  
    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;
    … …  
    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;
    … …  
    4946    protected HttpClient activeConnection;
    5047    protected IOAuthParameters oAuth20Parameters;
    51 
    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     }
    7948
    8049    /**
    … …  
    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(() ->
    … …  
    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);
    197             }
    198             counter++;
     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());
     153            }
     154        } catch (InterruptedException e) {
     155            Thread.currentThread().interrupt();
     156            Logging.trace(e);
     157            consumer.accept(Optional.empty());
     158            throw new MissingOAuthAccessTokenException(e);
    199159        }
    200160    }
    … …  
    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        }
  • trunk/src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java

    r19652 r19707  
    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);
    141                 }
    142                 if (keySet.contains(parametersKey)) {
    143                     Config.getPref().removeSensitive(parametersKey);
    144141                }
    145142            }
    … …  
    147144            final String hostKey = "oauth.access-token.object." + accessToken.getOAuthType() + "." + host;
    148145            final String parametersKey = "oauth.access-token.parameters." + accessToken.getOAuthType() + "." + host;
     146            // the parameters first: listeners of the token, like UserIdentityManager, find them in place
     147            Config.getPref().put(parametersKey, accessToken.getParameters().toPreferencesString());
     148            Config.getPref().addSensitive(this, parametersKey);
    149149            Config.getPref().put(hostKey, accessToken.toPreferencesString());
    150             Config.getPref().put(parametersKey, accessToken.getParameters().toPreferencesString());
    151150            Config.getPref().addSensitive(this, hostKey);
    152             Config.getPref().addSensitive(this, parametersKey);
    153151        }
    154152    }
  • trunk/src/org/openstreetmap/josm/tools/ExceptionUtil.java

    r19225 r19707  
    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>"
Note: See TracChangeset for help on using the changeset viewer.