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