001 // License: GPL. For details, see LICENSE file. 002 package org.openstreetmap.josm.io.auth; 003 004 import java.net.Authenticator; 005 import java.net.PasswordAuthentication; 006 import java.util.HashMap; 007 import java.util.Map; 008 009 import org.openstreetmap.josm.Main; 010 011 /** 012 * This is the default authenticator used in JOSM. It delegates lookup of credentials 013 * for the OSM API and an optional proxy server to the currently configured 014 * {@link CredentialsManager}. 015 * 016 */ 017 public class DefaultAuthenticator extends Authenticator { 018 private static DefaultAuthenticator instance; 019 020 public static DefaultAuthenticator getInstance() { 021 return instance; 022 } 023 024 public static void createInstance() { 025 instance = new DefaultAuthenticator(); 026 } 027 028 private final Map<RequestorType, Boolean> credentialsTried = new HashMap<RequestorType, Boolean>(); 029 private boolean enabled = true; 030 031 private DefaultAuthenticator() { 032 } 033 034 /** 035 * Called by the Java http stack when either the OSM API server or a proxy requires 036 * authentication. 037 * 038 */ 039 @Override protected PasswordAuthentication getPasswordAuthentication() { 040 if (!enabled) 041 return null; 042 try { 043 if (getRequestorType().equals(Authenticator.RequestorType.SERVER)) { 044 // if we are working with OAuth we don't prompt for a password 045 // 046 String authMethod = Main.pref.get("osm-server.auth-method", "basic"); 047 if (authMethod.equals("oauth")) 048 return null; 049 } 050 boolean tried = credentialsTried.get(getRequestorType()) != null; 051 CredentialsAgentResponse response = CredentialsManager.getInstance().getCredentials(getRequestorType(), getRequestingHost(), tried); 052 if (response == null || response.isCanceled()) 053 return null; 054 credentialsTried.put(getRequestorType(), true); 055 return new PasswordAuthentication(response.getUsername(), response.getPassword()); 056 } catch(CredentialsAgentException e) { 057 e.printStackTrace(); 058 return null; 059 } 060 } 061 062 public boolean isEnabled() { 063 return enabled; 064 } 065 066 public void setEnabled(boolean enabled) { 067 this.enabled = enabled; 068 } 069 }