Search in sources :

Example 66 with Authenticator

use of java.net.Authenticator in project cxf by apache.

the class CXFAuthenticatorCleanupTest method runCleanupTestWeakRef.

@Test
public void runCleanupTestWeakRef() throws Exception {
    InetAddress add = InetAddress.getLocalHost();
    final List<Integer> traceLengths = new ArrayList<>();
    // create a chain of CXFAuthenticators, strongly referenced to prevent cleanups
    Authenticator.setDefault(new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            traceLengths.add(Thread.currentThread().getStackTrace().length);
            return super.getPasswordAuthentication();
        }
    });
    Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    for (int x = 0; x < 20; x++) {
        CXFAuthenticator.addAuthenticator();
        CXFAuthenticator.instance = null;
        System.gc();
    }
    CXFAuthenticator.addAuthenticator();
    System.gc();
    Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    CXFAuthenticator.instance = null;
    for (int x = 0; x < 10; x++) {
        System.gc();
        Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    }
    Assert.assertEquals(12, traceLengths.size());
    // first trace would be just the raw authenticator above
    int raw = traceLengths.get(0);
    // second trace should still have an Authenticator added
    int one = traceLengths.get(1);
    // after clear and gc's
    int none = traceLengths.get(traceLengths.size() - 1);
    /*stacktrace for one should be different with raw
         * but the stracktrace length in java 8 and java 9-plus
         * isn't identical
         * so previous assertion one < (raw + (20 * 2)
         * isn't applicable for java 9-plus
         */
    Assert.assertTrue(one != raw);
    Assert.assertTrue(one > raw);
    Assert.assertTrue(one > none);
    Assert.assertEquals(raw, none);
}
Also used : ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication) Test(org.junit.Test)

Example 67 with Authenticator

use of java.net.Authenticator in project cxf by apache.

the class CXFAuthenticatorCleanupTest method runCleanupTestStrongRef.

@Test
public void runCleanupTestStrongRef() throws Exception {
    final List<Integer> traceLengths = new ArrayList<>();
    // create a chain of CXFAuthenticators, strongly referenced to prevent cleanups
    Authenticator.setDefault(new Authenticator() {

        protected PasswordAuthentication getPasswordAuthentication() {
            traceLengths.add(Thread.currentThread().getStackTrace().length);
            return super.getPasswordAuthentication();
        }
    });
    InetAddress add = InetAddress.getLocalHost();
    Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    List<CXFAuthenticator> list = new ArrayList<>();
    for (int x = 0; x < 20; x++) {
        CXFAuthenticator.addAuthenticator();
        list.add(CXFAuthenticator.instance);
        CXFAuthenticator.instance = null;
    }
    Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    for (int x = 9; x > 0; x -= 2) {
        list.remove(x);
    }
    for (int x = 0; x < 10; x++) {
        System.gc();
        Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    }
    list.clear();
    for (int x = 0; x < 10; x++) {
        System.gc();
        Authenticator.requestPasswordAuthentication("localhost", add, 8080, "http", "hello", "http");
    }
    Assert.assertEquals(22, traceLengths.size());
    // first trace would be just the raw authenticator above
    int raw = traceLengths.get(0);
    // second would be the trace with ALL the auths
    int all = traceLengths.get(1);
    // after remove of 5 and some gc's
    int some = traceLengths.get(11);
    // after clear and gc's
    int none = traceLengths.get(traceLengths.size() - 1);
    // System.out.println(traceLengths);
    // all should be A LOT above raw
    Assert.assertTrue(all > (raw + 20 * 3));
    Assert.assertTrue(all > raw);
    Assert.assertTrue(all > some);
    Assert.assertTrue(some > none);
    Assert.assertEquals(raw, none);
}
Also used : ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication) Test(org.junit.Test)

Example 68 with Authenticator

use of java.net.Authenticator in project java-cloudant by cloudant.

the class HttpProxyTest method setAuthenticatorIfNeeded.

/**
 * The Proxy-Authorization header that we add to requests gets encrypted in the case of a SSL
 * tunnel connection to a HTTPS server. The default HttpURLConnection does not add the header
 * to the CONNECT request so in that case we require an Authenticator to provide credentials
 * to the proxy server. The client code does not set an Authenticator automatically because
 * it is a global default so it must be set by the application developer or system
 * administrators in accordance with their environment. For the purposes of this test we can
 * add and remove the Authenticator before and after testing.
 */
@BeforeEach
public void setAuthenticatorIfNeeded(final boolean okUsable, final boolean useSecureProxy, final boolean useHttpsServer, final boolean useProxyAuth) {
    // we need to set the default Authenticator
    if (useProxyAuth && useHttpsServer && !isOkUsable) {
        // Allow https tunnelling through http proxy for the duration of the test
        System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                if (getRequestorType() == RequestorType.PROXY) {
                    return new PasswordAuthentication(mockProxyUser, mockProxyPass.toCharArray());
                } else {
                    return null;
                }
            }
        });
    }
}
Also used : ProxyAuthenticator(org.littleshoot.proxy.ProxyAuthenticator) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 69 with Authenticator

use of java.net.Authenticator in project coprhd-controller by CoprHD.

the class RecoverPointConnection method connect.

/**
 * Connect to RP and return a handle that can be used for FAPI calls
 *
 * @param endpoint - Address to connect to
 * @param username - Username for credentials
 * @param password - Password for credentials
 *
 * @return FunctionalAPIImpl - A handle for FAPI access
 */
public FunctionalAPIImpl connect(URI endpoint, String username, String password) {
    try {
        ignoreCertifications();
    // interceptCertificates();
    } catch (Exception e) {
    // so what?
    }
    String destAddress = endpoint.toASCIIString();
    try {
        URL baseUrl = FunctionalAPIImplService.class.getResource(".");
        URL url = new URL(baseUrl, destAddress);
        final String finalUser = username;
        final String finalPassword = password;
        // Modify the System Property for Max Redirects to a smaller number so we don't hammer
        // the device over and over unnecessarily with bad credentials (if they're bad) as this
        // takes a long time. Default is 20 redirects.
        // However we will save the old redirect value and restore it after we're done.
        String oldMaxRedirectsValue = null;
        try {
            oldMaxRedirectsValue = System.getProperty(SYSPROPS_HTTP_MAX_REDIRECTS);
        } catch (NullPointerException npe) {
            logger.warn("The System property " + SYSPROPS_HTTP_MAX_REDIRECTS + " does not already exist for some reason.");
        }
        // Set the Property for http.maxRedirects to 2 to prevent unnecessary retries
        System.setProperty(SYSPROPS_HTTP_MAX_REDIRECTS, NEW_MAX_REDIRECTS);
        // If we're creating a new connection, we want to clear the cache as it may be holding
        // onto a previously valid connection.
        AuthCacheValue.setAuthCache(new AuthCacheImpl());
        Authenticator.setDefault(null);
        // Create a PasswordAuthentication so when the request is asked via HTTP for authentication,
        // the below will be automatically returned. This is set here, but invoked behind the scenes.
        Authenticator.setDefault(new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(finalUser, finalPassword.toCharArray());
            }
        });
        logger.info("Attempting to connect to service " + FAPI_SERVICENAME + " at url " + FAPI_URL + " using auth credentials for: " + finalUser);
        // Connect to the service
        FunctionalAPIImplService service = new FunctionalAPIImplService(url, new QName(FAPI_URL, FAPI_SERVICENAME));
        FunctionalAPIImpl impl = service.getFunctionalAPIImplPort();
        BindingProvider bp = (BindingProvider) impl;
        Map<String, Object> map = bp.getRequestContext();
        logger.info("RecoverPoint service: Dest: " + destAddress + ", user: " + username);
        map.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, destAddress);
        map.put(BindingProvider.USERNAME_PROPERTY, username);
        map.put(BindingProvider.PASSWORD_PROPERTY, password);
        // Reset the System Property for http.maxRedirects, but only if an existing value was present
        if (oldMaxRedirectsValue != null && !oldMaxRedirectsValue.isEmpty()) {
            System.setProperty(SYSPROPS_HTTP_MAX_REDIRECTS, oldMaxRedirectsValue);
        }
        logger.info("Connected.");
        return impl;
    } catch (MalformedURLException e) {
        logger.error("Failed to create URL for the wsdl Location: " + destAddress);
        logger.error(e.getMessage());
        return null;
    }
}
Also used : AuthCacheImpl(sun.net.www.protocol.http.AuthCacheImpl) MalformedURLException(java.net.MalformedURLException) QName(javax.xml.namespace.QName) BindingProvider(javax.xml.ws.BindingProvider) FunctionalAPIImplService(com.emc.fapiclient.ws.FunctionalAPIImplService) KeyStoreException(java.security.KeyStoreException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) KeyManagementException(java.security.KeyManagementException) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) NoSuchProviderException(java.security.NoSuchProviderException) URL(java.net.URL) FunctionalAPIImpl(com.emc.fapiclient.ws.FunctionalAPIImpl) Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Example 70 with Authenticator

use of java.net.Authenticator in project tycho by eclipse.

the class ProxyServiceFacadeImpl method registerAuthenticator.

private void registerAuthenticator(final String user, final String password) {
    if (user == null || password == null) {
        return;
    }
    Authenticator authenticator = new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password.toCharArray());
        }
    };
    // not exactly pretty but this is how org.eclipse.core.net does it
    Authenticator.setDefault(authenticator);
}
Also used : Authenticator(java.net.Authenticator) PasswordAuthentication(java.net.PasswordAuthentication)

Aggregations

Authenticator (java.net.Authenticator)80 PasswordAuthentication (java.net.PasswordAuthentication)50 URL (java.net.URL)18 Proxy (java.net.Proxy)14 InetSocketAddress (java.net.InetSocketAddress)12 HttpClient (java.net.http.HttpClient)11 Field (java.lang.reflect.Field)10 HttpURLConnection (java.net.HttpURLConnection)10 IOException (java.io.IOException)9 Test (org.junit.Test)7 Method (java.lang.reflect.Method)6 File (java.io.File)5 SocketAddress (java.net.SocketAddress)5 InputStream (java.io.InputStream)4 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArrayList (java.util.ArrayList)3 Content (org.sonatype.goodies.httpfixture.server.jetty.behaviour.Content)3 Debug (org.sonatype.goodies.httpfixture.server.jetty.behaviour.Debug)3 JCommander (com.beust.jcommander.JCommander)2