Java 类org.apache.http.auth.AuthOption 实例源码

项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthentication() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));
    Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

    final Queue<AuthOption> options = this.authState.getAuthOptions();
    Assert.assertNotNull(options);
    final AuthOption option1 = options.poll();
    Assert.assertNotNull(option1);
    Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
    final AuthOption option2 = options.poll();
    Assert.assertNotNull(option2);
    Assert.assertEquals("basic", option2.getAuthScheme().getSchemeName());
    Assert.assertNull(options.poll());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthenticationNoMatchingChallenge() throws Exception {
    final HttpHost host = new HttpHost("somehost", 80);
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));
    response.addHeader(new BasicHeader(AUTH.WWW_AUTH, "whatever realm=\"realm1\", stuff=\"1234\""));

    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();

    this.authState.setState(AuthProtocolState.CHALLENGED);
    this.authState.update(new BasicScheme(), this.credentials);

    Assert.assertTrue(this.httpAuthenticator.handleAuthChallenge(host,
            response, authStrategy, this.authState, this.context));
    Assert.assertEquals(AuthProtocolState.CHALLENGED, this.authState.getState());

    final Queue<AuthOption> options = this.authState.getAuthOptions();
    Assert.assertNotNull(options);
    final AuthOption option1 = options.poll();
    Assert.assertNotNull(option1);
    Assert.assertEquals("digest", option1.getAuthScheme().getSchemeName());
    Assert.assertNull(options.poll());
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthChallengeStateOneOptions() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    this.authState.setState(AuthProtocolState.CHALLENGED);
    final LinkedList<AuthOption> authOptions = new LinkedList<AuthOption>();
    authOptions.add(new AuthOption(this.authScheme, this.credentials));
    this.authState.update(authOptions);

    Mockito.when(this.authScheme.authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));

    this.httpAuthenticator.generateAuthResponse(request, authState, context);

    Assert.assertSame(this.authScheme, this.authState.getAuthScheme());
    Assert.assertSame(this.credentials, this.authState.getCredentials());
    Assert.assertNull(this.authState.getAuthOptions());

    Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

    Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context);
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testSelectNoCredentialsProvider() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testNoCredentials() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    context.setCredentialsProvider(credentialsProvider);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
项目:java-http-signature    文件:HttpSignatureAuthenticationStrategy.java   
@Override
public Queue<AuthOption> select(final Map<String, Header> challengeHeaders,
                                final HttpHost authhost,
                                final HttpResponse response,
                                final HttpContext context)
        throws MalformedChallengeException {
    final HttpClientContext httpClientContext = HttpClientContext.adapt(context);
    final AuthState state = httpClientContext.getTargetAuthState();
    final Queue<AuthOption> queue = new LinkedList<>();

    if (state == null || !state.getState().equals(AuthProtocolState.CHALLENGED)) {
        queue.add(authOption);
    } else {
        System.out.println("does this happen?");
    }

    return queue;
}
项目:cyberduck    文件:CallbackProxyAuthenticationStrategy.java   
@Override
public Queue<AuthOption> select(final Map<String, Header> challenges, final HttpHost authhost, final HttpResponse response, final HttpContext context) throws MalformedChallengeException {
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if(registry == null) {
        return options;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = config.getProxyPreferredAuthSchemes();
    if(authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if(log.isDebugEnabled()) {
        log.debug("Authentication schemes in the order of preference: " + authPrefs);
    }

    for(final String id : authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT));
        if(challenge != null) {
            final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
            if(authSchemeProvider == null) {
                continue;
            }
            final AuthScheme authScheme = authSchemeProvider.create(context);
            authScheme.processChallenge(challenge);
            final Credentials saved = keychain.getCredentials(authhost.getHostName());
            if(StringUtils.isEmpty(saved.getPassword())) {
                try {
                    final Credentials input = prompt.prompt(bookmark,
                        StringUtils.EMPTY,
                        String.format("%s %s", LocaleFactory.localizedString("Login", "Login"), authhost.getHostName()),
                        authScheme.getRealm(),
                        new LoginOptions()
                            .icon(bookmark.getProtocol().disk())
                            .usernamePlaceholder(LocaleFactory.localizedString("Username", "Credentials"))
                            .passwordPlaceholder(LocaleFactory.localizedString("Password", "Credentials"))
                            .user(true).password(true)
                    );
                    if(input.isSaved()) {
                        context.setAttribute(PROXY_CREDENTIALS_INPUT_ID, input);
                    }
                    options.add(new AuthOption(authScheme, new NTCredentials(input.getUsername(), input.getPassword(),
                        preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain"))));
                }
                catch(LoginCanceledException ignored) {
                    // Ignore dismiss of prompt
                    throw new MalformedChallengeException(ignored.getMessage(), ignored);
                }
            }
            else {
                options.add(new AuthOption(authScheme, new NTCredentials(saved.getUsername(), saved.getPassword(),
                    preferences.getProperty("webdav.ntlm.workstation"), preferences.getProperty("webdav.ntlm.domain"))));
            }
        }
        else {
            if(log.isDebugEnabled()) {
                log.debug("Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}
项目:remote-files-sync    文件:AuthenticationStrategyImpl.java   
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");
    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if (registry == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Auth scheme registry not set in the context");
        }
        return options;
    }
    final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Credentials provider not set in the context");
        }
        return options;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = getPreferredAuthSchemes(config);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Authentication schemes in the order of preference: " + authPrefs);
    }

    for (final String id: authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
        if (challenge != null) {
            final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
            if (authSchemeProvider == null) {
                if (Log.isLoggable(TAG, Log.WARN)) {
                    Log.w(TAG, "Authentication scheme " + id + " not supported");
                    // Try again
                }
                continue;
            }
            final AuthScheme authScheme = authSchemeProvider.create(context);
            authScheme.processChallenge(challenge);

            final AuthScope authScope = new AuthScope(
                    authhost.getHostName(),
                    authhost.getPort(),
                    authScheme.getRealm(),
                    authScheme.getSchemeName());

            final Credentials credentials = credsProvider.getCredentials(authScope);
            if (credentials != null) {
                options.add(new AuthOption(authScheme, credentials));
            }
        } else {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}
项目:purecloud-iot    文件:AuthenticationStrategyImpl.java   
@Override
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");
    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if (registry == null) {
        this.log.debug("Auth scheme registry not set in the context");
        return options;
    }
    final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = getPreferredAuthSchemes(config);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
    }

    for (final String id: authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT));
        if (challenge != null) {
            final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
            if (authSchemeProvider == null) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication scheme " + id + " not supported");
                    // Try again
                }
                continue;
            }
            final AuthScheme authScheme = authSchemeProvider.create(context);
            authScheme.processChallenge(challenge);

            final AuthScope authScope = new AuthScope(
                    authhost.getHostName(),
                    authhost.getPort(),
                    authScheme.getRealm(),
                    authScheme.getSchemeName());

            final Credentials credentials = credsProvider.getCredentials(authScope);
            if (credentials != null) {
                options.add(new AuthOption(authScheme, credentials));
            }
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}
项目:purecloud-iot    文件:TestHttpAuthenticator.java   
@Test
public void testAuthChallengeStateMultipleOption() throws Exception {
    final HttpRequest request = new BasicHttpRequest("GET", "/");
    this.authState.setState(AuthProtocolState.CHALLENGED);

    final LinkedList<AuthOption> authOptions = new LinkedList<AuthOption>();
    final ContextAwareAuthScheme authScheme1 = Mockito.mock(ContextAwareAuthScheme.class);
    Mockito.doThrow(new AuthenticationException()).when(authScheme1).authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class));
    final ContextAwareAuthScheme authScheme2 = Mockito.mock(ContextAwareAuthScheme.class);
    Mockito.when(authScheme2.authenticate(
            Mockito.any(Credentials.class),
            Mockito.any(HttpRequest.class),
            Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff"));
    authOptions.add(new AuthOption(authScheme1, this.credentials));
    authOptions.add(new AuthOption(authScheme2, this.credentials));
    this.authState.update(authOptions);

    this.httpAuthenticator.generateAuthResponse(request, authState, context);

    Assert.assertSame(authScheme2, this.authState.getAuthScheme());
    Assert.assertSame(this.credentials, this.authState.getCredentials());
    Assert.assertNull(this.authState.getAuthOptions());

    Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP));

    Mockito.verify(authScheme1, Mockito.times(1)).authenticate(this.credentials, request, this.context);
    Mockito.verify(authScheme2, Mockito.times(1)).authenticate(this.credentials, request, this.context);
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testSelectNoSchemeRegistry() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("locahost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"test\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm1\", nonce=\"1234\""));

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(0, options.size());
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testCredentialsFound() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("somehost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope("somehost", 80, "realm2"),
            new UsernamePasswordCredentials("user", "pwd"));
    context.setCredentialsProvider(credentialsProvider);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(1, options.size());
    final AuthOption option = options.remove();
    Assert.assertTrue(option.getAuthScheme() instanceof DigestScheme);
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testUnsupportedScheme() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final HttpHost authhost = new HttpHost("somehost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\""));
    challenges.put("whatever", new BasicHeader(AUTH.WWW_AUTH, "Whatever realm=\"realm3\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope("somehost", 80),
            new UsernamePasswordCredentials("user", "pwd"));
    context.setCredentialsProvider(credentialsProvider);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(2, options.size());
    final AuthOption option1 = options.remove();
    Assert.assertTrue(option1.getAuthScheme() instanceof DigestScheme);
    final AuthOption option2 = options.remove();
    Assert.assertTrue(option2.getAuthScheme() instanceof BasicScheme);
}
项目:purecloud-iot    文件:TestAuthenticationStrategy.java   
@Test
public void testCustomAuthPreference() throws Exception {
    final TargetAuthenticationStrategy authStrategy = new TargetAuthenticationStrategy();
    final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
    final RequestConfig config = RequestConfig.custom()
        .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
        .build();

    final HttpHost authhost = new HttpHost("somehost", 80);
    final HttpClientContext context = HttpClientContext.create();

    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=\"realm1\""));
    challenges.put("digest", new BasicHeader(AUTH.WWW_AUTH, "Digest realm=\"realm2\", nonce=\"1234\""));

    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
        .register("basic", new BasicSchemeFactory())
        .register("digest", new DigestSchemeFactory()).build();
    context.setAuthSchemeRegistry(authSchemeRegistry);
    context.setRequestConfig(config);

    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope("somehost", 80),
            new UsernamePasswordCredentials("user", "pwd"));
    context.setCredentialsProvider(credentialsProvider);

    final Queue<AuthOption> options = authStrategy.select(challenges, authhost, response, context);
    Assert.assertNotNull(options);
    Assert.assertEquals(1, options.size());
    final AuthOption option1 = options.remove();
    Assert.assertTrue(option1.getAuthScheme() instanceof BasicScheme);
}
项目:lams    文件:AuthenticationStrategyAdaptor.java   
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    if (challenges == null) {
        throw new IllegalArgumentException("Map of auth challenges may not be null");
    }
    if (authhost == null) {
        throw new IllegalArgumentException("Host may not be null");
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    Queue<AuthOption> options = new LinkedList<AuthOption>();
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
            ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }

    AuthScheme authScheme;
    try {
        authScheme = this.handler.selectScheme(challenges, response, context);
    } catch (AuthenticationException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn(ex.getMessage(), ex);
        }
        return options;
    }
    String id = authScheme.getSchemeName();
    Header challenge = challenges.get(id.toLowerCase(Locale.US));
    authScheme.processChallenge(challenge);

    AuthScope authScope = new AuthScope(
            authhost.getHostName(),
            authhost.getPort(),
            authScheme.getRealm(),
            authScheme.getSchemeName());

    Credentials credentials = credsProvider.getCredentials(authScope);
    if (credentials != null) {
        options.add(new AuthOption(authScheme, credentials));
    }
    return options;
}
项目:lams    文件:AuthenticationStrategyImpl.java   
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    if (challenges == null) {
        throw new IllegalArgumentException("Map of auth challenges may not be null");
    }
    if (authhost == null) {
        throw new IllegalArgumentException("Host may not be null");
    }
    if (response == null) {
        throw new IllegalArgumentException("HTTP response may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }

    Queue<AuthOption> options = new LinkedList<AuthOption>();
    AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute(
            ClientContext.AUTHSCHEME_REGISTRY);
    if (registry == null) {
        this.log.debug("Auth scheme registry not set in the context");
        return options;
    }
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
            ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }

    @SuppressWarnings("unchecked")
    List<String> authPrefs = (List<String>) response.getParams().getParameter(this.prefParamName);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Authentication schemes in the order of preference: " + authPrefs);
    }

    for (String id: authPrefs) {
        Header challenge = challenges.get(id.toLowerCase(Locale.US));
        if (challenge != null) {
            try {
                AuthScheme authScheme = registry.getAuthScheme(id, response.getParams());
                authScheme.processChallenge(challenge);

                AuthScope authScope = new AuthScope(
                        authhost.getHostName(),
                        authhost.getPort(),
                        authScheme.getRealm(),
                        authScheme.getSchemeName());

                Credentials credentials = credsProvider.getCredentials(authScope);
                if (credentials != null) {
                    options.add(new AuthOption(authScheme, credentials));
                }
            } catch (IllegalStateException e) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication scheme " + id + " not supported");
                    // Try again
                }
            }
        } else {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}
项目:lams    文件:HttpAuthenticator.java   
public boolean authenticate(
        final HttpHost host,
        final HttpResponse response,
        final AuthenticationStrategy authStrategy,
        final AuthState authState,
        final HttpContext context) {
    try {
        if (this.log.isDebugEnabled()) {
            this.log.debug(host.toHostString() + " requested authentication");
        }
        Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
        if (challenges.isEmpty()) {
            this.log.debug("Response contains no authentication challenges");
            return false;
        }

        AuthScheme authScheme = authState.getAuthScheme();
        switch (authState.getState()) {
        case FAILURE:
            return false;
        case SUCCESS:
            authState.reset();
            break;
        case CHALLENGED:
        case HANDSHAKE:
            if (authScheme == null) {
                this.log.debug("Auth scheme is null");
                authStrategy.authFailed(host, null, context);
                authState.reset();
                authState.setState(AuthProtocolState.FAILURE);
                return false;
            }
        case UNCHALLENGED:
            if (authScheme != null) {
                String id = authScheme.getSchemeName();
                Header challenge = challenges.get(id.toLowerCase(Locale.US));
                if (challenge != null) {
                    this.log.debug("Authorization challenge processed");
                    authScheme.processChallenge(challenge);
                    if (authScheme.isComplete()) {
                        this.log.debug("Authentication failed");
                        authStrategy.authFailed(host, authState.getAuthScheme(), context);
                        authState.reset();
                        authState.setState(AuthProtocolState.FAILURE);
                        return false;
                    } else {
                        authState.setState(AuthProtocolState.HANDSHAKE);
                        return true;
                    }
                } else {
                    authState.reset();
                    // Retry authentication with a different scheme
                }
            }
        }
        Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
        if (authOptions != null && !authOptions.isEmpty()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Selected authentication options: " + authOptions);
            }
            authState.setState(AuthProtocolState.CHALLENGED);
            authState.update(authOptions);
            return true;
        } else {
            return false;
        }
    } catch (MalformedChallengeException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn("Malformed challenge: " +  ex.getMessage());
        }
        authState.reset();
        return false;
    }
}
项目:purecloud-iot    文件:AuthenticationStrategyAdaptor.java   
@Override
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(
            ClientContext.CREDS_PROVIDER);
    if (credsProvider == null) {
        this.log.debug("Credentials provider not set in the context");
        return options;
    }

    final AuthScheme authScheme;
    try {
        authScheme = this.handler.selectScheme(challenges, response, context);
    } catch (final AuthenticationException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn(ex.getMessage(), ex);
        }
        return options;
    }
    final String id = authScheme.getSchemeName();
    final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT));
    authScheme.processChallenge(challenge);

    final AuthScope authScope = new AuthScope(
            authhost.getHostName(),
            authhost.getPort(),
            authScheme.getRealm(),
            authScheme.getSchemeName());

    final Credentials credentials = credsProvider.getCredentials(authScope);
    if (credentials != null) {
        options.add(new AuthOption(authScheme, credentials));
    }
    return options;
}
项目:purecloud-iot    文件:HttpAuthenticator.java   
public boolean handleAuthChallenge(
        final HttpHost host,
        final HttpResponse response,
        final AuthenticationStrategy authStrategy,
        final AuthState authState,
        final HttpContext context) {
    try {
        if (this.log.isDebugEnabled()) {
            this.log.debug(host.toHostString() + " requested authentication");
        }
        final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
        if (challenges.isEmpty()) {
            this.log.debug("Response contains no authentication challenges");
            return false;
        }

        final AuthScheme authScheme = authState.getAuthScheme();
        switch (authState.getState()) {
        case FAILURE:
            return false;
        case SUCCESS:
            authState.reset();
            break;
        case CHALLENGED:
        case HANDSHAKE:
            if (authScheme == null) {
                this.log.debug("Auth scheme is null");
                authStrategy.authFailed(host, null, context);
                authState.reset();
                authState.setState(AuthProtocolState.FAILURE);
                return false;
            }
        case UNCHALLENGED:
            if (authScheme != null) {
                final String id = authScheme.getSchemeName();
                final Header challenge = challenges.get(id.toLowerCase(Locale.ROOT));
                if (challenge != null) {
                    this.log.debug("Authorization challenge processed");
                    authScheme.processChallenge(challenge);
                    if (authScheme.isComplete()) {
                        this.log.debug("Authentication failed");
                        authStrategy.authFailed(host, authState.getAuthScheme(), context);
                        authState.reset();
                        authState.setState(AuthProtocolState.FAILURE);
                        return false;
                    } else {
                        authState.setState(AuthProtocolState.HANDSHAKE);
                        return true;
                    }
                } else {
                    authState.reset();
                    // Retry authentication with a different scheme
                }
            }
        }
        final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
        if (authOptions != null && !authOptions.isEmpty()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Selected authentication options: " + authOptions);
            }
            authState.setState(AuthProtocolState.CHALLENGED);
            authState.update(authOptions);
            return true;
        } else {
            return false;
        }
    } catch (final MalformedChallengeException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn("Malformed challenge: " +  ex.getMessage());
        }
        authState.reset();
        return false;
    }
}
项目:purecloud-iot    文件:TestMainClientExec.java   
@Before
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    mainClientExec = new MainClientExec(requestExecutor, connManager, reuseStrategy,
        keepAliveStrategy, proxyHttpProcessor, targetAuthStrategy, proxyAuthStrategy, userTokenHandler);
    target = new HttpHost("foo", 80);
    proxy = new HttpHost("bar", 8888);

    Mockito.when(connManager.requestConnection(
            Mockito.<HttpRoute>any(), Mockito.any())).thenReturn(connRequest);
    Mockito.when(connRequest.get(
            Mockito.anyLong(), Mockito.<TimeUnit>any())).thenReturn(managedConn);
    final Map<String, Header> challenges = new HashMap<String, Header>();
    challenges.put("basic", new BasicHeader(AUTH.WWW_AUTH, "Basic realm=test"));
    final AuthOption authOption = new AuthOption(
            new BasicScheme(), new UsernamePasswordCredentials("user:pass"));
    Mockito.when(targetAuthStrategy.getChallenges(
            Mockito.eq(target),
            Mockito.<HttpResponse>any(),
            Mockito.<HttpClientContext>any())).thenReturn(challenges);
    Mockito.when(targetAuthStrategy.getChallenges(
            Mockito.eq(target),
            Mockito.<HttpResponse>any(),
            Mockito.<HttpClientContext>any())).thenReturn(challenges);
    Mockito.when(targetAuthStrategy.select(
            Mockito.same(challenges),
            Mockito.eq(target),
            Mockito.<HttpResponse>any(),
            Mockito.<HttpClientContext>any())).thenReturn(
            new LinkedList<AuthOption>(Arrays.asList(authOption)));
    Mockito.when(proxyAuthStrategy.getChallenges(
            Mockito.eq(proxy),
            Mockito.<HttpResponse>any(),
            Mockito.<HttpClientContext>any())).thenReturn(challenges);
    Mockito.when(proxyAuthStrategy.getChallenges(
            Mockito.eq(proxy),
            Mockito.<HttpResponse>any(),
            Mockito.<HttpClientContext>any())).thenReturn(challenges);
    Mockito.when(proxyAuthStrategy.select(
            Mockito.same(challenges),
            Mockito.eq(proxy),
            Mockito.<HttpResponse>any(),
            Mockito.<HttpClientContext>any())).thenReturn(
            new LinkedList<AuthOption>(Arrays.asList(authOption)));

}
项目:Visit    文件:AuthenticationStrategyImpl.java   
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");
    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if (registry == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Auth scheme registry not set in the context");
        }
        return options;
    }
    final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Credentials provider not set in the context");
        }
        return options;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = getPreferredAuthSchemes(config);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Authentication schemes in the order of preference: " + authPrefs);
    }

    for (final String id: authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
        if (challenge != null) {
            final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
            if (authSchemeProvider == null) {
                if (Log.isLoggable(TAG, Log.WARN)) {
                    Log.w(TAG, "Authentication scheme " + id + " not supported");
                    // Try again
                }
                continue;
            }
            final AuthScheme authScheme = authSchemeProvider.create(context);
            authScheme.processChallenge(challenge);

            final AuthScope authScope = new AuthScope(
                    authhost.getHostName(),
                    authhost.getPort(),
                    authScheme.getRealm(),
                    authScheme.getSchemeName());

            final Credentials credentials = credsProvider.getCredentials(authScope);
            if (credentials != null) {
                options.add(new AuthOption(authScheme, credentials));
            }
        } else {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}
项目:ZTLib    文件:AuthenticationStrategyImpl.java   
public Queue<AuthOption> select(
        final Map<String, Header> challenges,
        final HttpHost authhost,
        final HttpResponse response,
        final HttpContext context) throws MalformedChallengeException {
    Args.notNull(challenges, "Map of auth challenges");
    Args.notNull(authhost, "Host");
    Args.notNull(response, "HTTP response");
    Args.notNull(context, "HTTP context");
    final HttpClientContext clientContext = HttpClientContext.adapt(context);

    final Queue<AuthOption> options = new LinkedList<AuthOption>();
    final Lookup<AuthSchemeProvider> registry = clientContext.getAuthSchemeRegistry();
    if (registry == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Auth scheme registry not set in the context");
        }
        return options;
    }
    final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
    if (credsProvider == null) {
        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "Credentials provider not set in the context");
        }
        return options;
    }
    final RequestConfig config = clientContext.getRequestConfig();
    Collection<String> authPrefs = getPreferredAuthSchemes(config);
    if (authPrefs == null) {
        authPrefs = DEFAULT_SCHEME_PRIORITY;
    }
    if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Authentication schemes in the order of preference: " + authPrefs);
    }

    for (final String id: authPrefs) {
        final Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
        if (challenge != null) {
            final AuthSchemeProvider authSchemeProvider = registry.lookup(id);
            if (authSchemeProvider == null) {
                if (Log.isLoggable(TAG, Log.WARN)) {
                    Log.w(TAG, "Authentication scheme " + id + " not supported");
                    // Try again
                }
                continue;
            }
            final AuthScheme authScheme = authSchemeProvider.create(context);
            authScheme.processChallenge(challenge);

            final AuthScope authScope = new AuthScope(
                    authhost.getHostName(),
                    authhost.getPort(),
                    authScheme.getRealm(),
                    authScheme.getSchemeName());

            final Credentials credentials = credsProvider.getCredentials(authScope);
            if (credentials != null) {
                options.add(new AuthOption(authScheme, credentials));
            }
        } else {
            if (Log.isLoggable(TAG, Log.DEBUG)) {
                Log.d(TAG, "Challenge for " + id + " authentication scheme not available");
                // Try again
            }
        }
    }
    return options;
}
项目:lams    文件:AuthenticationStrategy.java   
/**
 * Selects one authentication challenge out of all available and
 * creates and generates {@link AuthOption} instance capable of
 * processing that challenge.
 *
 * @param challenges collection of challenges.
 * @param authhost authentication host.
 * @param response HTTP response.
 * @param context HTTP context.
 * @return authentication auth schemes that can be used for authentication. Can be empty.
 * @throws MalformedChallengeException if one of the authentication
 *  challenges is not valid or malformed.
 */
Queue<AuthOption> select(
        Map<String, Header> challenges,
        HttpHost authhost,
        HttpResponse response,
        HttpContext context) throws MalformedChallengeException;
项目:remote-files-sync    文件:AuthenticationStrategy.java   
/**
 * Selects one authentication challenge out of all available and
 * creates and generates {@link AuthOption} instance capable of
 * processing that challenge.
 *
 * @param challenges collection of challenges.
 * @param authhost authentication host.
 * @param response HTTP response.
 * @param context HTTP context.
 * @return authentication auth schemes that can be used for authentication. Can be empty.
 * @throws MalformedChallengeException if one of the authentication
 *  challenges is not valid or malformed.
 */
Queue<AuthOption> select(
        Map<String, Header> challenges,
        HttpHost authhost,
        HttpResponse response,
        HttpContext context) throws MalformedChallengeException;
项目:purecloud-iot    文件:AuthenticationStrategy.java   
/**
 * Selects one authentication challenge out of all available and
 * creates and generates {@link AuthOption} instance capable of
 * processing that challenge.
 *
 * @param challenges collection of challenges.
 * @param authhost authentication host.
 * @param response HTTP response.
 * @param context HTTP context.
 * @return authentication auth schemes that can be used for authentication. Can be empty.
 * @throws MalformedChallengeException if one of the authentication
 *  challenges is not valid or malformed.
 */
Queue<AuthOption> select(
        Map<String, Header> challenges,
        HttpHost authhost,
        HttpResponse response,
        HttpContext context) throws MalformedChallengeException;
项目:Visit    文件:AuthenticationStrategy.java   
/**
 * Selects one authentication challenge out of all available and
 * creates and generates {@link AuthOption} instance capable of
 * processing that challenge.
 *
 * @param challenges collection of challenges.
 * @param authhost authentication host.
 * @param response HTTP response.
 * @param context HTTP context.
 * @return authentication auth schemes that can be used for authentication. Can be empty.
 * @throws MalformedChallengeException if one of the authentication
 *  challenges is not valid or malformed.
 */
Queue<AuthOption> select(
        Map<String, Header> challenges,
        HttpHost authhost,
        HttpResponse response,
        HttpContext context) throws MalformedChallengeException;
项目:java-http-signature    文件:HttpSignatureAuthenticationStrategy.java   
/**
 * Creates a new instance using the passed authentication scheme.
 *
 * @param authScheme authentication scheme to use to authenticate
 *                   requests (expecting {@link HttpSignatureAuthScheme})
 * @param credentials credentials containing the HTTP Signature username
 */
public HttpSignatureAuthenticationStrategy(final AuthScheme authScheme,
                                           final Credentials credentials) {
    this.authOption = new AuthOption(authScheme, credentials);
}
项目:ZTLib    文件:AuthenticationStrategy.java   
/**
 * Selects one authentication challenge out of all available and
 * creates and generates {@link AuthOption} instance capable of
 * processing that challenge.
 *
 * @param challenges collection of challenges.
 * @param authhost authentication host.
 * @param response HTTP response.
 * @param context HTTP context.
 * @return authentication auth schemes that can be used for authentication. Can be empty.
 * @throws MalformedChallengeException if one of the authentication
 *  challenges is not valid or malformed.
 */
Queue<AuthOption> select(
        Map<String, Header> challenges,
        HttpHost authhost,
        HttpResponse response,
        HttpContext context) throws MalformedChallengeException;