public void testIsAuthenticationDialogSuppressed() throws Exception { final boolean[] suppressed = new boolean[1]; Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { suppressed[0] = NetworkSettings.isAuthenticationDialogSuppressed(); return super.getPasswordAuthentication(); } }); Callable<Void> callable = new Callable<Void>() { @Override public Void call() throws Exception { Authenticator.requestPasswordAuthentication("wher.ev.er", Inet4Address.getByName("1.2.3.4"), 1234, "http", null, "http"); return null; } }; NetworkSettings.suppressAuthenticationDialog(callable); assertTrue(suppressed[0]); }
private static PasswordAuthentication getSystemCreds( final AuthScope authscope, final Authenticator.RequestorType requestorType) { final String hostname = authscope.getHost(); final int port = authscope.getPort(); final String protocol = port == 443 ? "https" : "http"; return Authenticator.requestPasswordAuthentication( hostname, null, port, protocol, null, translateScheme(authscope.getScheme()), null, requestorType); }
private static PasswordAuthentication privilegedRequestPasswordAuthentication( final String host, final InetAddress addr, final int port, final String protocol, final String prompt, final String scheme, final URL url, final RequestorType authType) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<PasswordAuthentication>() { public PasswordAuthentication run() { if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Requesting Authentication: host =" + host + " url = " + url); } PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( host, addr, port, protocol, prompt, scheme, url, authType); if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); } return pass; } }); }
private void getAnswer() { if (!answered) { answered = true; PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication( hci.host, hci.addr, hci.port, hci.protocol, hci.prompt, hci.scheme, hci.url, hci.authType); /** * To be compatible with existing callback handler implementations, * when the underlying Authenticator is canceled, username and * password are assigned null. No exception is thrown. */ if (passAuth != null) { username = passAuth.getUserName(); password = passAuth.getPassword(); } } }
@Override public Credential authenticate( Proxy proxy, URL url, List<Challenge> challenges) throws IOException { for (Challenge challenge : challenges) { if (!"Basic".equalsIgnoreCase(challenge.getScheme())) { continue; } PasswordAuthentication auth = Authenticator.requestPasswordAuthentication(url.getHost(), getConnectToInetAddress(proxy, url), url.getPort(), url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.SERVER); if (auth != null) { return Credential.basic(auth.getUserName(), new String(auth.getPassword())); } } return null; }
@Override public Credential authenticateProxy( Proxy proxy, URL url, List<Challenge> challenges) throws IOException { for (Challenge challenge : challenges) { if (!"Basic".equalsIgnoreCase(challenge.getScheme())) { continue; } InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address(); PasswordAuthentication auth = Authenticator.requestPasswordAuthentication( proxyAddress.getHostName(), getConnectToInetAddress(proxy, url), proxyAddress.getPort(), url.getProtocol(), challenge.getRealm(), challenge.getScheme(), url, Authenticator.RequestorType.PROXY); if (auth != null) { return Credential.basic(auth.getUserName(), new String(auth.getPassword())); } } return null; }
/** * Constructor an un-schemed object for site access. */ public HttpCallerInfo(URL url, Authenticator a) { this.url= url; prompt = ""; host = url.getHost(); int p = url.getPort(); if (p == -1) { port = url.getDefaultPort(); } else { port = p; } InetAddress ia; try { ia = InetAddress.getByName(url.getHost()); } catch (Exception e) { ia = null; } addr = ia; protocol = url.getProtocol(); authType = RequestorType.SERVER; scheme = ""; authenticator = a; }
private void getAnswer() { if (!answered) { answered = true; PasswordAuthentication passAuth = Authenticator.requestPasswordAuthentication( hci.authenticator, hci.host, hci.addr, hci.port, hci.protocol, hci.prompt, hci.scheme, hci.url, hci.authType); /** * To be compatible with existing callback handler implementations, * when the underlying Authenticator is canceled, username and * password are assigned null. No exception is thrown. */ if (passAuth != null) { username = passAuth.getUserName(); password = passAuth.getPassword(); } } }
public static void main (String args[]) throws Exception { Authenticator defaultAuth = Authenticator.getDefault(); if (defaultAuth != null) { throw new RuntimeException("Unexpected authenticator: null expected"); } MyAuthenticator auth = new MyAuthenticator(); Authenticator.setDefault(auth); defaultAuth = Authenticator.getDefault(); if (defaultAuth != auth) { throw new RuntimeException("Unexpected authenticator: auth expected"); } System.setSecurityManager(new SecurityManager()); try { defaultAuth = Authenticator.getDefault(); throw new RuntimeException("Expected security exception not raised"); } catch (AccessControlException s) { System.out.println("Got expected exception: " + s); if (!s.getPermission().equals(new NetPermission("requestPasswordAuthentication"))) { throw new RuntimeException("Unexpected permission check: " + s.getPermission()); } } System.out.println("Test passed with default authenticator " + defaultAuth); }
private static ProxyTunnelServer setupProxy() throws IOException { ProxyTunnelServer pserver = new ProxyTunnelServer(); /* * register a system wide authenticator and setup the proxy for * authentication */ Authenticator.setDefault(new TestAuthenticator()); // register with the username and password pserver.needUserAuth(true); pserver.setUserAuth("Test", "test123"); pserver.start(); return pserver; }
@Override public void runWithAuthenticator( Authenticator authenticator, Runnable target ) { try{ Authenticator.setDefault( authenticator ); target.run(); }finally{ SESecurityManager.installAuthenticator(); } }
/** * Constructor. * * @param oldAuth The wrapped authenticator. * * @throws NoSuchFieldException Unable to access wrapped authenticator data. */ private GitAuth(Authenticator oldAuth) throws NoSuchFieldException { this.oldAuth = oldAuth; // Getting the fields with java reflection requestingHost = Authenticator.class.getDeclaredField("requestingHost"); requestingSite = Authenticator.class.getDeclaredField("requestingSite"); requestingPort = Authenticator.class.getDeclaredField("requestingPort"); requestingProtocol = Authenticator.class.getDeclaredField("requestingProtocol"); requestingPrompt = Authenticator.class.getDeclaredField("requestingPrompt"); requestingScheme = Authenticator.class.getDeclaredField("requestingScheme"); requestingURL = Authenticator.class.getDeclaredField("requestingURL"); requestingAuthType = Authenticator.class.getDeclaredField("requestingAuthType"); // Making the fields accessible requestingHost.setAccessible(true); requestingSite.setAccessible(true); requestingPort.setAccessible(true); requestingProtocol.setAccessible(true); requestingPrompt.setAccessible(true); requestingScheme.setAccessible(true); requestingURL.setAccessible(true); requestingAuthType.setAccessible(true); }
/** * Installs my custom authenticator. Gets the current authenticator by * reflection and compares it with the previous one. If they are not the same * instance, then my authenticator will be installed. If not, then it means * that my authenticator is already installed */ public static void install() { final Authenticator[] currentAuth = new Authenticator[1]; try { Field declaredField = Authenticator.class.getDeclaredField("theAuthenticator"); declaredField.setAccessible(true); currentAuth[0] = (Authenticator) declaredField.get(null); if (currentAuth[0] == null || currentAuth[0] != installedAuthenticator) { GitAuth oldInstalledAuth = installedAuthenticator; installedAuthenticator = new GitAuth(currentAuth[0]); installedAuthenticator.setBoundHosts(oldInstalledAuth.getBoundHosts()); Authenticator.setDefault(installedAuthenticator); } } catch (Throwable e) { if (logger.isDebugEnabled()) { logger.debug(e, e); } } }
@Test public void testUserPassword() throws Exception { startServer(buildUserPasswordConfig()); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("oryx", "pass".toCharArray()); } }); try { String response = Resources.toString( new URL("http://localhost:" + getHTTPPort() + "/helloWorld"), StandardCharsets.UTF_8); assertEquals("Hello, World", response); } finally { Authenticator.setDefault(null); } }
private static PasswordAuthentication privilegedRequestPasswordAuthentication( final String host, final InetAddress addr, final int port, final String protocol, final String prompt, final String scheme, final URL url, final RequestorType authType) { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<>() { public PasswordAuthentication run() { if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Requesting Authentication: host =" + host + " url = " + url); } PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( host, addr, port, protocol, prompt, scheme, url, authType); if (logger.isLoggable(PlatformLogger.Level.FINEST)) { logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); } return pass; } }); }
@Test public void authenticate() throws Exception { server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_UNAUTHORIZED) .addHeader("www-authenticate: Basic realm=\"protected area\"") .setBody("Please authenticate.")); server.enqueue(new MockResponse().setBody("Successful auth!")); Authenticator.setDefault(new RecordingAuthenticator()); urlFactory.setClient(urlFactory.client().newBuilder() .authenticator(new JavaNetAuthenticator()) .build()); connection = urlFactory.open(server.url("/").url()); assertEquals("Successful auth!", readAscii(connection.getInputStream(), Integer.MAX_VALUE)); RecordedRequest denied = server.takeRequest(); assertNull(denied.getHeader("Authorization")); RecordedRequest accepted = server.takeRequest(); assertEquals("GET / HTTP/1.1", accepted.getRequestLine()); assertEquals("Basic " + RecordingAuthenticator.BASE_64_CREDENTIALS, accepted.getHeader("Authorization")); }
private List<String> authCallsForHeader(String authHeader) throws IOException { boolean proxy = authHeader.startsWith("Proxy-"); int responseCode = proxy ? 407 : 401; RecordingAuthenticator authenticator = new RecordingAuthenticator(null); Authenticator.setDefault(authenticator); MockResponse pleaseAuthenticate = new MockResponse() .setResponseCode(responseCode) .addHeader(authHeader) .setBody("Please authenticate."); server.enqueue(pleaseAuthenticate); urlFactory.setClient(urlFactory.client().newBuilder() .authenticator(new JavaNetAuthenticator()) .build()); if (proxy) { urlFactory.setClient(urlFactory.client().newBuilder() .proxy(server.toProxyAddress()) .build()); connection = urlFactory.open(new URL("http://android.com")); } else { connection = urlFactory.open(server.url("/").url()); } assertEquals(responseCode, connection.getResponseCode()); connection.getErrorStream().close(); return authenticator.calls; }
public static void setProxy(String type, final String host, final int port, final String user, final String pwd) { if (type != null && host != null) { Proxy.Type proxyType = Enum.valueOf(Proxy.Type.class, type.toUpperCase()); javaNetProxy = new Proxy(proxyType, new InetSocketAddress(host, port)); Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, pwd.toCharArray()); } }); if (user != null && pwd != null) { proxyCredentials = new BasicCredentialsProvider(); proxyCredentials.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, pwd)); } apacheHttpProxy = new HttpHost(host, port, proxyType.name()); } }
public Credentials getCredentials(final AuthScope authscope) { Args.notNull(authscope, "Auth scope"); final Credentials localcreds = internal.getCredentials(authscope); if (localcreds != null) { return localcreds; } if (authscope.getHost() != null) { PasswordAuthentication systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.SERVER); if (systemcreds == null) { systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.PROXY); } if (systemcreds != null) { return new UsernamePasswordCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword())); } } return null; }
protected HttpURLConnection createConnection(String wsPart, String method) throws Exception { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(LOGIN, PWD.toCharArray()); } }); log.debug(method + ": " + getOpenbravoURL() + wsPart); final URL url = new URL(getOpenbravoURL() + wsPart); final HttpURLConnection hc = (HttpURLConnection) url.openConnection(); hc.setRequestMethod(method); hc.setAllowUserInteraction(false); hc.setDefaultUseCaches(false); hc.setDoOutput(true); hc.setDoInput(true); hc.setInstanceFollowRedirects(true); hc.setUseCaches(false); hc.setRequestProperty("Content-Type", "application/json"); return hc; }
private HttpURLConnection createConnection(String wsPart, String method) throws Exception { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(LOGIN, PWD.toCharArray()); } }); final URL url = new URL(getOpenbravoURL() + wsPart); final HttpURLConnection hc = (HttpURLConnection) url.openConnection(); hc.setRequestMethod(method); hc.setAllowUserInteraction(false); hc.setDefaultUseCaches(false); hc.setDoOutput(true); hc.setDoInput(true); hc.setInstanceFollowRedirects(true); hc.setUseCaches(false); hc.setRequestProperty("Content-Type", "text/xml"); return hc; }
/** * Creates a HTTP connection. * * @param wsPart * @param method * POST, PUT, GET or DELETE * @return the created connection * @throws Exception */ protected HttpURLConnection createConnection(String wsPart, String method) throws Exception { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(LOGIN, PWD.toCharArray()); } }); log.debug(method + ": " + getOpenbravoURL() + wsPart); final URL url = new URL(getOpenbravoURL() + wsPart); final HttpURLConnection hc = (HttpURLConnection) url.openConnection(); hc.setRequestMethod(method); hc.setAllowUserInteraction(false); hc.setDefaultUseCaches(false); hc.setDoOutput(true); hc.setDoInput(true); hc.setInstanceFollowRedirects(true); hc.setUseCaches(false); hc.setRequestProperty("Content-Type", "text/xml"); return hc; }
public void enableWebdavAuthentication(final String username, final char[] password) { webdavAuthenticationActive = true; Authenticator.setDefault(new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication(){ try { if(webdavAuthenticationActive && getRequestingURL().getHost().equals(new URL(soapServerURL).getHost())){ return new PasswordAuthentication(username, password); } } catch (MalformedURLException e) { e.printStackTrace(); } return null; } }); }
private static void setProxyProperties(Properties properties) { for (String property : PROXY_PROPERTIES) { if (properties.containsKey(property)) { System.setProperty(property, properties.get(property).toString()); } } final String userName = System.getProperty("http.proxyUser"); final String password = System.getProperty("http.proxyPassword"); if (userName != null && password != null) { Authenticator.setDefault(new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(userName, password.toCharArray()); } }); } }
private HttpURLConnection createConnection(final String location) throws IOException { URL url = new URL(location); HttpURLConnection conn; if (proxyHost != null && proxyPort != null) { if (proxyUser != null && proxyPassword != null) { Authenticator authenticator = new Authenticator() { @Override public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(proxyUser, proxyPassword.toCharArray()); } }; Authenticator.setDefault(authenticator); } Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); conn = (HttpURLConnection) url.openConnection(proxy); } else { conn = (HttpURLConnection) url.openConnection(); } return conn; }
/** * Create a new Camera object. * @param name * @param url * @param username * @param password * @param refreshRate */ public Camera ( String name, String url, String username, String password, long refreshRate ) { this.cameraName = name; // Set the camera name. this.cameraURLString = url; // Set the camera URL. this.username = username; // Set the camera username. this.password = password; // Set the camera password. this.refreshRate = refreshRate; // Set the desired refresh rate. try { // Create a new URL object from the URL-string of our camera. cameraURL = new URL( this.cameraURLString ); } catch( MalformedURLException m ) { this.error = true; } // Check if this camera requires authentication. // If so, then create and set the authenticator object. if ( !username.equals("") && !password.equals("") ) { this.authenticator = new MyAuthenticator( this.username, this.password ); Authenticator.setDefault( this.authenticator ); } }