Example usage for org.apache.http.client CredentialsProvider getCredentials

List of usage examples for org.apache.http.client CredentialsProvider getCredentials

Introduction

In this page you can find the example usage for org.apache.http.client CredentialsProvider getCredentials.

Prototype

Credentials getCredentials(AuthScope authscope);

Source Link

Document

Get the Credentials credentials for the given authentication scope.

Usage

From source file:com.rightscale.provider.rest.DashboardSession.java

private HttpRequestInterceptor createBasicAuthInterceptor() {
    return new HttpRequestInterceptor() {
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }/* w  w w.  j a  v  a2 s . c  o m*/
            }
        }
    };
}

From source file:com.github.pascalgn.jiracli.web.HttpClient.java

private void setCredentials() {
    AuthState authState = httpClientContext.getTargetAuthState();
    if (authState != null) {
        CredentialsProvider credentialsProvider = httpClientContext.getCredentialsProvider();
        AuthScope authScope = new AuthScope(HttpHost.create(getBaseUrl()));
        org.apache.http.auth.Credentials credentials = credentialsProvider.getCredentials(authScope);
        if (credentials != null) {
            authState.update(new BasicScheme(), credentials);
            authState.setState(AuthProtocolState.CHALLENGED);
        }//  w  ww . j av a 2  s . co m
    }
}

From source file:fr.univsavoie.ltp.client.LoginActivity.java

/**
 * Pav de code permetant de se connecter de faon scuris au serveur
 */// w w w.  j a v  a  2 s  .c  o  m
private void auth() {
    try {
        HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        };

        // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Enable HTTP parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        httpClient = new DefaultHttpClient(ccm, params);

        CredentialsProvider authCred = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials(login.getText().toString(),
                password.getText().toString());
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (Exception e) {
        Log.e("Catch", "Auth: " + e.getLocalizedMessage());
    }
}

From source file:org.janusgraph.diskstorage.es.rest.RestClientSetupTest.java

@Test
public void testHttpBasicAuthConfiguration() throws Exception {

    // testing that the appropriate values are passed to the client builder via credentials provider
    final String testRealm = "testRealm";
    final String testUser = "testUser";
    final String testPassword = "testPassword";

    final CredentialsProvider cp = basicAuthTestBase(ImmutableMap.<String, String>builder().build(), testRealm,
            testUser, testPassword);/*from ww  w .j ava 2s.  co m*/

    final Credentials credentials = cp
            .getCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, testRealm));
    assertNotNull(credentials);
    assertEquals(testUser, credentials.getUserPrincipal().getName());
    assertEquals(testPassword, credentials.getPassword());
}

From source file:net.oauth.client.httpclient4.PreemptiveAuthorizer.java

/**
 * If no auth scheme has been selected for the given context, consider each
 * of the preferred auth schemes and select the first one for which an
 * AuthScheme and matching Credentials are available.
 *//* w  w w  .  j av a2s . c  o  m*/
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (authState != null && authState.getAuthScheme() != null) {
        return;
    }
    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    CredentialsProvider creds = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
    for (Object schemeName : (Iterable) context.getAttribute(ClientContext.AUTH_SCHEME_PREF)) {
        AuthScheme scheme = schemes.getAuthScheme(schemeName.toString(), request.getParams());
        if (scheme != null) {
            AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(),
                    scheme.getSchemeName());
            Credentials cred = creds.getCredentials(targetScope);
            if (cred != null) {
                authState.setAuthScheme(scheme);
                authState.setCredentials(cred);
                return;
            }
        }
    }
}

From source file:org.dataconservancy.archive.impl.fcrepo.ri.MultiThreadedHttpClient.java

public MultiThreadedHttpClient(HttpClientConfig config) {
    this.config = config;
    if (config.getPreemptiveAuthN()) {
        HttpRequestInterceptor interceptor = new HttpRequestInterceptor() {
            @Override/*from  w ww.  j a v  a  2 s .com*/
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
                // If no auth scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };
        addRequestInterceptor(interceptor, 0);
    }

}

From source file:glaze.oauth.PreemptiveAuthorizer.java

/**
 * If no auth scheme has been selected for the given context, consider each
 * of the preferred auth schemes and select the first one for which an
 * AuthScheme and matching Credentials are available.
 *//*from  w  w  w .ja  v a2s  . co  m*/
@SuppressWarnings("unchecked")
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

    if (authState != null && authState.getAuthScheme() != null) {
        return;
    }

    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    CredentialsProvider provider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY);
    HttpParams params = request.getParams();

    for (String schemeName : (Iterable<String>) params.getParameter(AuthPNames.PROXY_AUTH_PREF)) {
        AuthScheme scheme = schemes.getAuthScheme(schemeName, params);
        if (scheme != null) {
            AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(),
                    scheme.getSchemeName());
            Credentials creds = provider.getCredentials(targetScope);

            if (creds != null) {
                authState.update(scheme, creds);
                return;
            }
        }
    }
}

From source file:org.xwiki.android.test.utils.xmlrpc.RestClient.java

/**
 * set user credentials with manually developed preemtive Auth
 *///from  w  w  w .  j ava2 s . c  o m
private void setCredentials() {
    // Setting preemtiveAuth manually since org.apache.http does not support it
    HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);

                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }

    };
    client.addRequestInterceptor(preemptiveAuth, 0);
    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM), defaultcreds);

}

From source file:org.xwiki.android.rest.HttpConnector.java

/**
 * set user credentials with manually developed preemtive Auth
 *//*from ww  w.ja va 2 s. c  om*/
private void setCredentials() {
    if (isSecured) {

        // Setting preemtiveAuth manually since org.apache.http does not support it
        preemptiveAuth = new HttpRequestInterceptor() {

            @Override
            public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };

        client.addRequestInterceptor(preemptiveAuth, 0);

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getCredentialsProvider().setCredentials(new AuthScope(null, -1, AuthScope.ANY_REALM),
                defaultcreds);
    }
}

From source file:fr.univsavoie.ltp.client.map.Session.java

/**
 * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS).
 * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...)
 *///from ww  w  .  j a v  a  2s . c  o  m
private void secureAuth() {
    try {
        // Instance de SharedPreferences pour lire les donnes dans un fichier
        SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE);
        String login = myPrefs.getString("Login", null);
        String password = myPrefs.getString("Password", null);

        HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {
                AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                if (authState.getAuthScheme() == null) {
                    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    Credentials creds = credsProvider.getCredentials(authScope);
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }
        };

        // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates
        SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null);
        sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Enable HTTP parameters
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object.
        SchemeRegistry registry = new SchemeRegistry();
        // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslFactory, 443));

        // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        httpClient = new DefaultHttpClient(ccm, params);

        CredentialsProvider authCred = new BasicCredentialsProvider();
        Credentials creds = new UsernamePasswordCredentials(login, password);
        authCred.setCredentials(AuthScope.ANY, creds);

        httpClient.addRequestInterceptor(preemptiveAuth, 0);
        httpClient.setCredentialsProvider(authCred);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}