Search in sources :

Example 11 with Credentials

use of org.apache.http.auth.Credentials in project apex-core by apache.

the class WebServicesClientTest method checkUserCredentials.

public static void checkUserCredentials(String username, String password, AuthScheme authScheme) throws NoSuchFieldException, IllegalAccessException {
    CredentialsProvider provider = getCredentialsProvider();
    String httpScheme = AuthScope.ANY_SCHEME;
    if (authScheme == AuthScheme.BASIC) {
        httpScheme = AuthSchemes.BASIC;
    } else if (authScheme == AuthScheme.DIGEST) {
        httpScheme = AuthSchemes.DIGEST;
    }
    AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
    Credentials credentials = provider.getCredentials(authScope);
    Assert.assertNotNull("Credentials", credentials);
    Assert.assertTrue("Credentials type is user", UsernamePasswordCredentials.class.isAssignableFrom(credentials.getClass()));
    UsernamePasswordCredentials pwdCredentials = (UsernamePasswordCredentials) credentials;
    Assert.assertEquals("Username", username, pwdCredentials.getUserName());
    Assert.assertEquals("Password", password, pwdCredentials.getPassword());
}
Also used : AuthScope(org.apache.http.auth.AuthScope) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 12 with Credentials

use of org.apache.http.auth.Credentials in project platform_external_apache-http by android.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
     * Creates a tunnel to the target server.
     * The connection must be established to the (last) proxy.
     * A CONNECT request for tunnelling through the proxy will
     * be created and sent, the response received and checked.
     * This method does <i>not</i> update the connection with
     * information about the tunnel, that is left to the caller.
     *
     * @param route     the route to establish
     * @param context   the context for request execution
     *
     * @return  <code>true</code> if the tunnelled route is secure,
     *          <code>false</code> otherwise.
     *          The implementation here always returns <code>false</code>,
     *          but derived classes may override.
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Example 13 with Credentials

use of org.apache.http.auth.Credentials in project apex-core by apache.

the class WebServicesClient method setupUserPassAuthScheme.

private static void setupUserPassAuthScheme(AuthScheme scheme, String httpScheme, AuthSchemeProvider provider, ConfigProvider configuration) {
    String username = configuration.getProperty(scheme, "username");
    String password = configuration.getProperty(scheme, "password");
    if ((username != null) && (password != null)) {
        LOG.info("Setting up scheme {}", scheme);
        AuthScope authScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, httpScheme);
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        setupHttpAuthScheme(httpScheme, provider, authScope, credentials);
    } else if ((username != null) || (password != null)) {
        LOG.warn("Not setting up scheme {}, missing credentials {}", scheme, (username == null) ? "username" : "password");
    }
}
Also used : AuthScope(org.apache.http.auth.AuthScope) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 14 with Credentials

use of org.apache.http.auth.Credentials in project jena by apache.

the class TestFusekiTestAuth method testServer_auth_bad_user.

@Test(expected = HttpException.class)
public void testServer_auth_bad_user() {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials("USERUSER", PASSWORD);
    credsProvider.setCredentials(AuthScope.ANY, credentials);
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try (TypedInputStream in = HttpOp.execHttpGet(FusekiTestAuth.urlDataset(), "*/*", client, null)) {
    } catch (HttpException ex) {
        throw assertAuthHttpException(ex);
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.jena.atlas.web.HttpException) FusekiTestAuth.assertAuthHttpException(org.apache.jena.fuseki.embedded.FusekiTestAuth.assertAuthHttpException) TypedInputStream(org.apache.jena.atlas.web.TypedInputStream) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Credentials(org.apache.http.auth.Credentials) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Test(org.junit.Test)

Example 15 with Credentials

use of org.apache.http.auth.Credentials in project karaf by apache.

the class SyncopeLoginModule method login.

public boolean login() throws LoginException {
    Callback[] callbacks = new Callback[2];
    callbacks[0] = new NameCallback("Username: ");
    callbacks[1] = new PasswordCallback("Password: ", false);
    try {
        callbackHandler.handle(callbacks);
    } catch (IOException ioException) {
        throw new LoginException(ioException.getMessage());
    } catch (UnsupportedCallbackException unsupportedCallbackException) {
        throw new LoginException(unsupportedCallbackException.getMessage() + " not available to obtain information from user.");
    }
    user = ((NameCallback) callbacks[0]).getName();
    char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
    if (tmpPassword == null) {
        tmpPassword = new char[0];
    }
    String password = new String(tmpPassword);
    principals = new HashSet<>();
    // authenticate the user on Syncope
    LOGGER.debug("Authenticate user {} on Syncope located {}", user, address);
    DefaultHttpClient client = new DefaultHttpClient();
    Credentials creds = new UsernamePasswordCredentials(user, password);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    HttpGet get = new HttpGet(address + "/users/self");
    get.setHeader("Content-Type", "application/xml");
    List<String> roles = new ArrayList<>();
    try {
        CloseableHttpResponse response = client.execute(get);
        LOGGER.debug("Syncope HTTP response status code: {}", response.getStatusLine().getStatusCode());
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            LOGGER.warn("User {} not authenticated", user);
            return false;
        }
        LOGGER.debug("User {} authenticated", user);
        LOGGER.debug("Populating principals with user");
        principals.add(new UserPrincipal(user));
        LOGGER.debug("Retrieving user {} roles", user);
        roles = extractingRoles(EntityUtils.toString(response.getEntity()));
    } catch (Exception e) {
        LOGGER.error("User {} authentication failed", user, e);
        throw new LoginException("User " + user + " authentication failed: " + e.getMessage());
    }
    LOGGER.debug("Populating principals with roles");
    for (String role : roles) {
        principals.add(new RolePrincipal(role));
    }
    return true;
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) UserPrincipal(org.apache.karaf.jaas.boot.principal.UserPrincipal) LoginException(javax.security.auth.login.LoginException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) LoginException(javax.security.auth.login.LoginException) RolePrincipal(org.apache.karaf.jaas.boot.principal.RolePrincipal) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Credentials(org.apache.http.auth.Credentials)

Aggregations

Credentials (org.apache.http.auth.Credentials)39 AuthScope (org.apache.http.auth.AuthScope)22 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)16 AuthScheme (org.apache.http.auth.AuthScheme)15 CredentialsProvider (org.apache.http.client.CredentialsProvider)13 AuthState (org.apache.http.auth.AuthState)11 AuthenticationException (org.apache.http.auth.AuthenticationException)9 HttpHost (org.apache.http.HttpHost)8 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)7 NTCredentials (org.apache.http.auth.NTCredentials)5 IOException (java.io.IOException)4 Header (org.apache.http.Header)4 HttpException (org.apache.http.HttpException)4 HttpRequest (org.apache.http.HttpRequest)4 HttpResponse (org.apache.http.HttpResponse)4 Scheme (org.apache.http.conn.scheme.Scheme)4 BasicScheme (org.apache.http.impl.auth.BasicScheme)4 HttpEntity (org.apache.http.HttpEntity)3 AbortableHttpRequest (org.apache.http.client.methods.AbortableHttpRequest)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3