1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io.auth;
|
---|
3 |
|
---|
4 | import java.net.Authenticator;
|
---|
5 | import java.net.PasswordAuthentication;
|
---|
6 | import java.util.EnumMap;
|
---|
7 | import java.util.Map;
|
---|
8 |
|
---|
9 | import org.openstreetmap.josm.Main;
|
---|
10 | import org.openstreetmap.josm.io.OsmApi;
|
---|
11 |
|
---|
12 | /**
|
---|
13 | * This is the default authenticator used in JOSM. It delegates lookup of credentials
|
---|
14 | * for the OSM API and an optional proxy server to the currently configured {@link CredentialsManager}.
|
---|
15 | * @since 2641
|
---|
16 | */
|
---|
17 | public final class DefaultAuthenticator extends Authenticator {
|
---|
18 | private static volatile DefaultAuthenticator instance;
|
---|
19 |
|
---|
20 | /**
|
---|
21 | * Returns the unique instance
|
---|
22 | * @return The unique instance
|
---|
23 | */
|
---|
24 | public static DefaultAuthenticator getInstance() {
|
---|
25 | return instance;
|
---|
26 | }
|
---|
27 |
|
---|
28 | /**
|
---|
29 | * Creates the unique instance
|
---|
30 | */
|
---|
31 | public static void createInstance() {
|
---|
32 | instance = new DefaultAuthenticator();
|
---|
33 | }
|
---|
34 |
|
---|
35 | private final Map<RequestorType, Boolean> credentialsTried = new EnumMap<>(RequestorType.class);
|
---|
36 | private boolean enabled = true;
|
---|
37 |
|
---|
38 | private DefaultAuthenticator() {
|
---|
39 | }
|
---|
40 |
|
---|
41 | /**
|
---|
42 | * Called by the Java HTTP stack when either the OSM API server or a proxy requires authentication.
|
---|
43 | */
|
---|
44 | @Override
|
---|
45 | protected PasswordAuthentication getPasswordAuthentication() {
|
---|
46 | if (!enabled)
|
---|
47 | return null;
|
---|
48 | try {
|
---|
49 | if (getRequestorType().equals(Authenticator.RequestorType.SERVER) && OsmApi.isUsingOAuth()) {
|
---|
50 | // if we are working with OAuth we don't prompt for a password
|
---|
51 | return null;
|
---|
52 | }
|
---|
53 | boolean tried = credentialsTried.get(getRequestorType()) != null;
|
---|
54 | CredentialsAgentResponse response = CredentialsManager.getInstance().getCredentials(getRequestorType(), getRequestingHost(), tried);
|
---|
55 | if (response == null || response.isCanceled())
|
---|
56 | return null;
|
---|
57 | credentialsTried.put(getRequestorType(), Boolean.TRUE);
|
---|
58 | return new PasswordAuthentication(response.getUsername(), response.getPassword());
|
---|
59 | } catch (CredentialsAgentException e) {
|
---|
60 | Main.error(e);
|
---|
61 | return null;
|
---|
62 | }
|
---|
63 | }
|
---|
64 |
|
---|
65 | public boolean isEnabled() {
|
---|
66 | return enabled;
|
---|
67 | }
|
---|
68 |
|
---|
69 | public void setEnabled(boolean enabled) {
|
---|
70 | this.enabled = enabled;
|
---|
71 | }
|
---|
72 | }
|
---|