Java Code Examples for java.net.Authenticator#setDefault()

The following examples show how to use java.net.Authenticator#setDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReferencingAuthenticator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private void remove() {
    try {
        for (final Field f : Authenticator.class.getDeclaredFields()) {
            if (f.getType().equals(Authenticator.class)) {
                try {
                    f.setAccessible(true);
                    Authenticator o = (Authenticator)f.get(null);
                    if (o == this) {
                        //this is at the root of any chain of authenticators
                        Authenticator.setDefault(wrapped);
                    } else {
                        removeFromChain(o);
                    }
                } catch (Exception e) {
                    //ignore
                }
            }
        }
    } catch (Throwable t) {
        //ignore
    }
}
 
Example 2
Source File: NetworkSettingsTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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]);
}
 
Example 3
Source File: Webi.java    From webi with Apache License 2.0 6 votes vote down vote up
public Webi setProxy(String host, int port, final String username, final String password) {
    webService.is_proxy_seted = true;
    webService.proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));
    System.setProperty("http.proxyHost", host);
    System.setProperty("http.proxyPort", String.valueOf(port));
    System.setProperty("http.proxyUser", username);
    System.setProperty("http.proxyPassword", password);

    Authenticator.setDefault(
            new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password.toCharArray());
                }
            }
    );
    return this;
}
 
Example 4
Source File: IvyAuthenticator.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
/**
 * Installs an <tt>IvyAuthenticator</tt> as default <tt>Authenticator</tt>. Call this method
 * before opening HTTP(S) connections to enable Ivy authentication.
 */
public static void install() {
    // We will try to use the original authenticator as backup authenticator.
    // Since there is no getter available, so try to use some reflection to
    // obtain it. If that doesn't work, assume there is no original authenticator
    Authenticator original = getCurrentAuthenticator();

    if (original instanceof IvyAuthenticator) {
        return;
    }

    try {
        Authenticator.setDefault(new IvyAuthenticator(original));
    } catch (SecurityException e) {
        if (!securityWarningLogged) {
            securityWarningLogged = true;
            Message.warn("Not enough permissions to set the IvyAuthenticator. "
                    + "HTTP(S) authentication will be disabled!");
        }
    }
}
 
Example 5
Source File: SoapService.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
private void initializeProxyAuthenticator(final String proxyUser, final String proxyPassword) {

        if (proxyUser != null && proxyPassword != null) {
            Authenticator.setDefault(
                    new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(
                            proxyUser, proxyPassword.toCharArray()
                    );
                }
            }
            );
            System.setProperty("http.proxyUser", proxyUser);
            System.setProperty("http.proxyPassword", proxyPassword);
        }
    }
 
Example 6
Source File: HttpsProxyStackOverflow.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static BadAuthProxyServer startServer() throws IOException {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("xyz", "xyz".toCharArray());
        }
        });

    BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0));
    Thread serverThread = new Thread(server);
    serverThread.start();
    return server;
}
 
Example 7
Source File: UploadMojo.java    From helm-maven-plugin with MIT License 5 votes vote down vote up
private void verifyAndSetAuthentication() throws MojoExecutionException {

		PasswordAuthentication authentication = getAuthentication(getHelmUploadRepo());
		if (authentication == null) {
			throw new IllegalArgumentException("Credentials has to be configured for uploading to Artifactory.");
		}

		Authenticator.setDefault(new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return authentication;
			}
		});
	}
 
Example 8
Source File: FtpService.java    From cerberus-source with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setProxy(FTPClient client, String system, AppService myResponse) {
    String proxyHost = parameterService.getParameterStringByKey("cerberus_proxy_host", "",
            DEFAULT_PROXY_HOST);
    int proxyPort = parameterService.getParameterIntegerByKey("cerberus_proxy_port", "",
            DEFAULT_PROXY_PORT);

    myResponse.setProxy(true);
    myResponse.setProxyHost(proxyHost);
    myResponse.setProxyPort(proxyPort);

    SocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
    Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    if (parameterService.getParameterBooleanByKey("cerberus_proxyauthentification_active", system,
            DEFAULT_PROXYAUTHENT_ACTIVATE)) {
        Authenticator.setDefault(
                new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                String proxyUser = parameterService.getParameterStringByKey("cerberus_proxyauthentification_user", "", DEFAULT_PROXYAUTHENT_USER);
                String proxyPassword = parameterService.getParameterStringByKey("cerberus_proxyauthentification_password", "", DEFAULT_PROXYAUTHENT_PASSWORD);
                myResponse.setProxyWithCredential(true);
                myResponse.setProxyUser(proxyUser);
                return new PasswordAuthentication(
                        proxyUser, proxyPassword.toCharArray()
                );
            }
        }
        );
    }
    client.setProxy(proxy);
}
 
Example 9
Source File: DefaultAuthenticator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static synchronized DefaultAuthenticator getAuthenticator() {
    if (instance == null) {
        instance = new DefaultAuthenticator();
        Authenticator.setDefault(instance);
    }
    counter++;
    return instance;
}
 
Example 10
Source File: DefaultAuthenticator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static synchronized DefaultAuthenticator getAuthenticator() {
    if (instance == null) {
        instance = new DefaultAuthenticator();
        Authenticator.setDefault(instance);
    }
    counter++;
    return instance;
}
 
Example 11
Source File: HttpsProxyStackOverflow.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static BadAuthProxyServer startServer() throws IOException {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("xyz", "xyz".toCharArray());
        }
        });

    BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0));
    Thread serverThread = new Thread(server);
    serverThread.start();
    return server;
}
 
Example 12
Source File: HttpsProxyStackOverflow.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
static BadAuthProxyServer startServer() throws IOException {
    Authenticator.setDefault(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("xyz", "xyz".toCharArray());
        }
        });

    BadAuthProxyServer server = new BadAuthProxyServer(new ServerSocket(0));
    Thread serverThread = new Thread(server);
    serverThread.start();
    return server;
}
 
Example 13
Source File: ProxyManager.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
public void uninstall() {
    if (seedProxySelector != null) {
        ProxySelector.setDefault(null);
    }
    if (seedProxyAuthenticator != null) {
        Authenticator.setDefault(null);
    }
}
 
Example 14
Source File: BasicLongCredentials.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);

        BasicAuthenticator a = new BasicAuthenticator(REALM) {
            public boolean checkCredentials (String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();

        Authenticator.setDefault(new MyAuthenticator());

        URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read()!= -1) { c ++; }

        if (c != 0) { throw new RuntimeException("Test failed c = " + c); }
        if (error) { throw new RuntimeException("Test failed: error"); }

        System.out.println ("OK");
    } finally {
        server.stop(0);
    }
}
 
Example 15
Source File: BasicLongCredentials.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);

        BasicAuthenticator a = new BasicAuthenticator(REALM) {
            public boolean checkCredentials (String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();

        Authenticator.setDefault(new MyAuthenticator());

        URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read()!= -1) { c ++; }

        if (c != 0) { throw new RuntimeException("Test failed c = " + c); }
        if (error) { throw new RuntimeException("Test failed: error"); }

        System.out.println ("OK");
    } finally {
        server.stop(0);
    }
}
 
Example 16
Source File: BasicLongCredentials.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
    try {
        Handler handler = new Handler();
        HttpContext ctx = server.createContext("/test", handler);

        BasicAuthenticator a = new BasicAuthenticator(REALM) {
            public boolean checkCredentials (String username, String pw) {
                return USERNAME.equals(username) && PASSWORD.equals(pw);
            }
        };
        ctx.setAuthenticator(a);
        server.start();

        Authenticator.setDefault(new MyAuthenticator());

        URL url = new URL("http://localhost:"+server.getAddress().getPort()+"/test/");
        HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
        InputStream is = urlc.getInputStream();
        int c = 0;
        while (is.read()!= -1) { c ++; }

        if (c != 0) { throw new RuntimeException("Test failed c = " + c); }
        if (error) { throw new RuntimeException("Test failed: error"); }

        System.out.println ("OK");
    } finally {
        server.stop(0);
    }
}
 
Example 17
Source File: BazelLibGenerator.java    From onos with Apache License 2.0 4 votes vote down vote up
private static String getHttpSha(String name, String urlStr, String algorithm) {
    try {
        MessageDigest md = MessageDigest.getInstance(algorithm);
        byte[] buffer = new byte[8192];

        URL url = new URL(urlStr);

        Optional<File> cache = Optional.ofNullable(System.getenv("ONOS_ROOT"))
                .map(Paths::get)
                .map(Stream::of)
                .orElseGet(Stream::empty)
                .map(Path::toFile)
                .filter(File::canRead)
                .findAny();

        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");

        URLConnection connection;
        String env_http_proxy = System.getenv("HTTP_PROXY");
        if (env_http_proxy != null) {
            List<String> proxyHostInfo = getProxyHostInfo(env_http_proxy);
            Proxy http_proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostInfo.get(0),
                                                                                Integer.valueOf(proxyHostInfo.get(1))));

            if ((proxyHostInfo.get(2) != null) && (proxyHostInfo.get(3) != null)) {
                Authenticator authenticator = new Authenticator() {
                    public PasswordAuthentication getPasswordAuthentication() {
                        return (new PasswordAuthentication(proxyHostInfo.get(2), proxyHostInfo.get(3).toCharArray()));
                    }
                };

                Authenticator.setDefault(authenticator);
            }

            connection = url.openConnection(http_proxy);
        } else {
            connection = url.openConnection();
        }

        connection.connect();
        InputStream stream = connection.getInputStream();

        int read;
        while ((read = stream.read(buffer)) >= 0) {
            md.update(buffer, 0, read);
        }
        StringBuilder result = new StringBuilder();
        byte[] digest = md.digest();
        for (byte b : digest) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    } catch (IOException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source File: HTTPDownloader.java    From microcks with Apache License 2.0 4 votes vote down vote up
/**
 * Prepare an URLConnection with all the seurity related stuffs specified by optional secret.
 */
private static HttpURLConnection prepareURLConnection(String remoteUrl, Secret secret, boolean disableSSLValidation) throws IOException {

   // Build remote URL and local target file.
   URL website = new URL(remoteUrl);

   // Set authenticator instance for proxies and stuffs.
   Authenticator.setDefault(new UsernamePasswordAuthenticator(username, password));

   HttpURLConnection connection = (HttpURLConnection) website.openConnection();

   // If SSL validation is disabled, trust everything.
   try {
      if (disableSSLValidation) {
         log.debug("SSL Validation is disabled for {}, installing accept everything TrustManager", remoteUrl);
         installAcceptEverythingTrustManager(connection);
      } else if (secret != null && secret.getCaCertPem() != null) {
         log.debug("Secret for {} contains a CA Cert, installing certificate into TrustManager", remoteUrl);
         installCustomCaCertTrustManager(secret.getCaCertPem(), connection);
      }
   } catch (Exception e) {
      log.error("Caught exception while preparing TrustManager for connecting {}: {}", remoteUrl, e.getMessage());
      throw new IOException("SSL Connection with " + remoteUrl + " failed during preparation", e);
   }

   if (secret != null) {
      // If Basic authentication required, set request property.
      if (secret.getUsername() != null && secret.getPassword() != null) {
         log.debug("Secret for {} contains username/password, assuming Authorization Basic", remoteUrl);
         // Building a base64 string.
         String encoded = Base64.getEncoder().encodeToString(
               (secret.getUsername() + ":" + secret.getPassword())
                     .getBytes(StandardCharsets.UTF_8));
         connection.setRequestProperty("Authorization", "Basic " + encoded);
      }

      // If Token authentication required, set request property.
      if (secret.getToken() != null) {
         if (secret.getTokenHeader() != null && secret.getTokenHeader().trim().length() > 0) {
            log.debug("Secret for {} contains token and token header, adding them as request header", remoteUrl);
            connection.setRequestProperty(secret.getTokenHeader().trim(), secret.getToken());
         } else {
            log.debug("Secret for {} contains token only, assuming Authorization Bearer", remoteUrl);
            connection.setRequestProperty("Authorization", "Bearer " + secret.getToken());
         }
      }
   }

   return connection;
}
 
Example 19
Source File: DefaultAuthenticator.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
public static synchronized void reset() {
    --counter;
    if (instance != null && counter == 0) {
        Authenticator.setDefault(systemAuthenticator);
    }
}
 
Example 20
Source File: SensorInternetVS.java    From gsn with GNU General Public License v3.0 4 votes vote down vote up
@Override
public boolean initialize() {
	TreeMap <  String , String > params = getVirtualSensorConfiguration( ).getMainClassInitialParams( ) ;
	String param = null;

	param = params.get(SI_URL);
	if (param != null)
		try {
			siUrl = new URL (param) ;
		} catch (MalformedURLException e) {
			logger.error(e.getMessage(), e);
			return false;
		}
		else {
			logger.error("The required parameter: >" + SI_URL + "<+ is missing from the virtual sensor configuration file.");
			return false;
		}

	param = params.get(SI_USERNAME) ;
	if (param != null) {
		siUsername = param ;
	}
	else {
		logger.error("The required parameter: >" + SI_USERNAME + "<+ is missing from the virtual sensor configuration file.");
		return false;
	}

	param = params.get(SI_PASSWORD);
	if (param != null) {
		siPassword = param;
	}
	else {
		logger.error("The required parameter: >" + SI_PASSWORD + "<+ is missing from the virtual sensor configuration file.");
		return false;
	}

	param = params.get(SI_STREAM_MAPPING) ;
	if (param != null) {
		siStreamMapping = initStreamMapping(param) ;
		if (siStreamMapping == null) {
			logger.error("Failed to parse the required parameter: >" + SI_STREAM_MAPPING + "< (" + param + ")");
			return false;
		}
	}
	else {
		logger.error("The required parameter: >" + SI_STREAM_MAPPING + "<+ is missing from the virtual sensor configuration file.");
		return false;
	}

	// Enabling Basic authentication
	Authenticator.setDefault(new Authenticator() {
		protected PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication (siUsername, siPassword.toCharArray());
		}
	});

	return true;
}