@Override public void setUsernamePassword(AuthenticationType authType, String username, String password) { this.credentials = new UsernamePasswordCredentials( Objects.requireNonNull(username), Objects.requireNonNull(password)); this.credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, credentials); RegistryBuilder<AuthSchemeProvider> authRegistryBuilder = RegistryBuilder.create(); switch (authType) { case BASIC: authRegistryBuilder.register(AuthSchemes.BASIC, new BasicSchemeFactory()); break; case DIGEST: authRegistryBuilder.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); break; default: throw new IllegalArgumentException("Unsupported authentiation type: " + authType); } this.authRegistry = authRegistryBuilder.build(); }
public static HttpClient build(byte[] token) { HttpClientBuilder builder = HttpClientBuilder.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new CollaredSPNegoSchemeFactory(token)).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() { @Override public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } }); builder.setDefaultCredentialsProvider(credentialsProvider); return builder.build(); }
public InternalHttpClient( final ClientExecChain execChain, final HttpClientConnectionManager connManager, final HttpRoutePlanner routePlanner, final Lookup<CookieSpecProvider> cookieSpecRegistry, final Lookup<AuthSchemeProvider> authSchemeRegistry, final CookieStore cookieStore, final CredentialsProvider credentialsProvider, final RequestConfig defaultConfig, final List<Closeable> closeables) { super(); Args.notNull(execChain, "HTTP client exec chain"); Args.notNull(connManager, "HTTP connection manager"); Args.notNull(routePlanner, "HTTP route planner"); this.execChain = execChain; this.connManager = connManager; this.routePlanner = routePlanner; this.cookieSpecRegistry = cookieSpecRegistry; this.authSchemeRegistry = authSchemeRegistry; this.cookieStore = cookieStore; this.credentialsProvider = credentialsProvider; this.defaultConfig = defaultConfig; this.closeables = closeables; }
@Before public void setUp() throws Exception { this.defltAuthStrategy = Mockito.mock(AuthenticationStrategy.class); this.authState = new AuthState(); this.authScheme = Mockito.mock(ContextAwareAuthScheme.class); Mockito.when(this.authScheme.getSchemeName()).thenReturn("Basic"); Mockito.when(this.authScheme.isComplete()).thenReturn(Boolean.TRUE); this.context = new BasicHttpContext(); this.defaultHost = new HttpHost("localhost", 80); this.context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.defaultHost); this.credentials = Mockito.mock(Credentials.class); this.credentialsProvider = new BasicCredentialsProvider(); this.credentialsProvider.setCredentials(AuthScope.ANY, this.credentials); this.context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); this.authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()) .register("ntlm", new NTLMSchemeFactory()).build(); this.context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); this.authCache = Mockito.mock(AuthCache.class); this.context.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache); this.httpAuthenticator = new HttpAuthenticator(); }
/** * Tests that the client will stop connecting to the server if * the server still keep asking for a valid ticket. */ @Test public void testDontTryToAuthenticateEndlessly() throws Exception { this.serverBootstrap.registerHandler("*", new PleaseNegotiateService()); final HttpHost target = start(); final AuthSchemeProvider nsf = new NegotiateSchemeProviderWithMockGssManager(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final Credentials use_jaas_creds = new UseJaasCredentials(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf) .build(); this.httpclient = HttpClients.custom() .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credentialsProvider) .build(); final String s = "/path"; final HttpGet httpget = new HttpGet(s); final HttpResponse response = this.httpclient.execute(target, httpget); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@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()); }
@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()); }
@SuppressWarnings("unchecked") @Test public void testExecuteLocalContext() throws Exception { final HttpGet httpget = new HttpGet("http://somehost/stuff"); final HttpClientContext context = HttpClientContext.create(); final Lookup<CookieSpecProvider> localCookieSpecRegistry = Mockito.mock(Lookup.class); final Lookup<AuthSchemeProvider> localAuthSchemeRegistry = Mockito.mock(Lookup.class); final CookieStore localCookieStore = Mockito.mock(CookieStore.class); final CredentialsProvider localCredentialsProvider = Mockito.mock(CredentialsProvider.class); final RequestConfig localConfig = RequestConfig.custom().build(); context.setCookieSpecRegistry(localCookieSpecRegistry); context.setAuthSchemeRegistry(localAuthSchemeRegistry); context.setCookieStore(localCookieStore); context.setCredentialsProvider(localCredentialsProvider); context.setRequestConfig(localConfig); client.execute(httpget, context); Assert.assertSame(localCookieSpecRegistry, context.getCookieSpecRegistry()); Assert.assertSame(localAuthSchemeRegistry, context.getAuthSchemeRegistry()); Assert.assertSame(localCookieStore, context.getCookieStore()); Assert.assertSame(localCredentialsProvider, context.getCredentialsProvider()); Assert.assertSame(localConfig, context.getRequestConfig()); }
private static HttpClientBuilder createBuilder() { if (isWinAuthAvailable()) { final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.NTLM, new WindowsNTLMSchemeFactory(null)) .register(AuthSchemes.SPNEGO, new WindowsNegotiateSchemeFactory(null)) .build(); final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider()); return HttpClientBuilder.create() .setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry); } else { return HttpClientBuilder.create(); } }
private HttpClient getHttpClient() { Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credsProvider).build(); return httpclient; }
protected final CloseableHttpClient getHttpClient(final boolean useSpnego) throws Exception { final CredentialsProvider credsProvider = new BasicCredentialsProvider(); final HttpClientBuilder hcb = HttpClients.custom(); if (useSpnego) { //SPNEGO/Kerberos setup log.debug("SPNEGO activated"); final AuthSchemeProvider nsf = new SPNegoSchemeFactory(true);// new NegotiateSchemeProvider(); final Credentials jaasCreds = new JaasCredentials(); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.SPNEGO), jaasCreds); credsProvider.setCredentials(new AuthScope(null, -1, null, AuthSchemes.NTLM), new NTCredentials("Guest", "Guest", "Guest", "Guest")); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf).register(AuthSchemes.NTLM, new NTLMSchemeFactory()).build(); hcb.setDefaultAuthSchemeRegistry(authSchemeRegistry); } hcb.setDefaultCredentialsProvider(credsProvider); hcb.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(10 * 1000).build()); final CloseableHttpClient httpClient = hcb.build(); return httpClient; }
/** * Set up authentication for HTTP Basic/HTTP Digest/SPNEGO. * * @param httpClientBuilder The client builder * @return The context * @throws HttpException */ private void setupAuthentication( HttpClientBuilder httpClientBuilder ) throws HttpException { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password)); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); if (authType == AuthType.always) { AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); HttpHost target = new HttpHost(host, port, isOverSsl ? "https" : "http"); authCache.put(target, basicAuth); // Add AuthCache to the execution context httpContext.setAuthCache(authCache); } else { if (!StringUtils.isNullOrEmpty(kerberosServicePrincipalName)) { GssClient gssClient = new GssClient(username, password, kerberosClientKeytab, krb5ConfFile); AuthSchemeProvider nsf = new SPNegoSchemeFactory(gssClient, kerberosServicePrincipalName, kerberosServicePrincipalType); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, nsf) .build(); httpClientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); } } }
public static void addSpnego(HttpClientBuilder clientBuilder) { //Add spnego http header processor Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider> create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); clientBuilder.setDefaultAuthSchemeRegistry(authSchemeRegistry); //There has to be at least this dummy credentials provider or apache http client gives up BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials()); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); }
@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; }
/** * Constructs an HTTP client with user specified by the given credentials. * * @param url The URL for the Avatica server * @param credential The GSS credentials */ public AvaticaCommonsHttpClientSpnegoImpl(URL url, GSSCredential credential) { this.url = Objects.requireNonNull(url); pool = new PoolingHttpClientConnectionManager(); // Increase max total connection to 100 final String maxCnxns = System.getProperty(CACHED_CONNECTIONS_MAX_KEY, CACHED_CONNECTIONS_MAX_DEFAULT); pool.setMaxTotal(Integer.parseInt(maxCnxns)); // Increase default max connection per route to 25 final String maxCnxnsPerRoute = System.getProperty(CACHED_CONNECTIONS_MAX_PER_ROUTE_KEY, CACHED_CONNECTIONS_MAX_PER_ROUTE_DEFAULT); pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute)); this.host = new HttpHost(url.getHost(), url.getPort()); this.authRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(STRIP_PORT_ON_SERVER_LOOKUP, USE_CANONICAL_HOSTNAME)).build(); this.credentialsProvider = new BasicCredentialsProvider(); if (null != credential) { // Non-null credential should be used directly with KerberosCredentials. this.credentialsProvider.setCredentials(AuthScope.ANY, new KerberosCredentials(credential)); } else { // A null credential implies that the user is logged in via JAAS using the // java.security.auth.login.config system property this.credentialsProvider.setCredentials(AuthScope.ANY, EmptyCredentials.INSTANCE); } this.authCache = new BasicAuthCache(); // A single thread-safe HttpClient, pooling connections via the ConnectionManager this.client = HttpClients.custom() .setDefaultAuthSchemeRegistry(authRegistry) .setConnectionManager(pool).build(); }
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; }
private KerberosHttpClient(String user, String password, String domain, String kdc) { try { File krb5Config = createKrb5Configuration(domain, kdc); File loginConfig = createLoginConfiguration(); System.setProperty("java.security.auth.login.config", loginConfig.toURI().toString()); System.setProperty("java.security.krb5.conf", krb5Config.toURI().toString()); System.setProperty("sun.security.krb5.debug", "false"); //Change this property to true, if you want debug output. System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); RegistryBuilder<AuthSchemeProvider> registryBuilder = RegistryBuilder.create(); String id = AuthSchemes.SPNEGO; SPNegoSchemeFactory schemeFactory = new SPNegoSchemeFactory(SKIP_PORT_AT_KERBEROS_DATABASE_LOOKUP); Lookup<AuthSchemeProvider> authSchemeRegistry = registryBuilder.register(id, schemeFactory).build(); client = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry) .setConnectionManager(createConnectionManager()).build(); httpContext = getHttpContext(); loginContext = getLoginContext(user, password); //without it, authentication will be failed. final Subject subject = loginContext.getSubject(); final HttpGet get = new HttpGet(KerberosBpmClient.this.rootUri); Subject.doAs(subject, this.privilegedExecute(get, httpContext)); } catch (Exception e) { logger.error("Can't create Kerberos client!"); e.printStackTrace(); throw new RuntimeException(e); } }
@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; }
/** * Javadoc specifies that {@link GSSContext#initSecContext(byte[], int, int)} can return null * if no token is generated. Client should be able to deal with this response. */ @Test public void testNoTokenGeneratedError() throws Exception { this.serverBootstrap.registerHandler("*", new PleaseNegotiateService()); final HttpHost target = start(); final AuthSchemeProvider nsf = new NegotiateSchemeProviderWithMockGssManager(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final Credentials use_jaas_creds = new UseJaasCredentials(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf) .build(); this.httpclient = HttpClients.custom() .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credentialsProvider) .build(); final String s = "/path"; final HttpGet httpget = new HttpGet(s); final HttpResponse response = this.httpclient.execute(target, httpget); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
@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); }
@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); }
@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); }
@Test(timeout=30000) // this timeout (in ms) needs to be extended if you're actively debugging the code public void testNoInfiniteLoopOnSPNOutsideDomain() throws Exception { Assume.assumeTrue("Test can only be run on Windows", WinHttpClients.isWinAuthAvailable()); // HTTPCLIENT-1545 // If a service principal name (SPN) from outside your Windows domain tree (e.g., HTTP/example.com) is used, // InitializeSecurityContext will return SEC_E_DOWNGRADE_DETECTED (decimal: -2146892976, hex: 0x80090350). // Because WindowsNegotiateScheme wasn't setting the completed state correctly when authentication fails, // HttpClient goes into an infinite loop, constantly retrying the negotiate authentication to kingdom // come. This error message, "The system detected a possible attempt to compromise security. Please ensure that // you can contact the server that authenticated you." is associated with SEC_E_DOWNGRADE_DETECTED. final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new AuthSchemeProvider() { @Override public AuthScheme create(final HttpContext context) { return new WindowsNegotiateSchemeGetTokenFail(AuthSchemes.SPNEGO, "HTTP/example.com"); } }).build(); final CredentialsProvider credsProvider = new WindowsCredentialsProvider(new SystemDefaultCredentialsProvider()); final CloseableHttpClient customClient = HttpClientBuilder.create() .setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry).build(); final HttpHost target = start(); final HttpGet httpGet = new HttpGet("/"); final CloseableHttpResponse response = customClient.execute(target, httpGet); try { EntityUtils.consume(response.getEntity()); } finally { response.close(); } }
protected CloseableHttpClient httpClientFactory() throws CannotInitializeDataAdapterException { try { SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory( createSslCustomContext(), null, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create(); schemeProviderBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(null, -1, null), new Credentials() { @Override public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } }); return HttpClients.custom() .setDefaultAuthSchemeRegistry(schemeProviderBuilder.build()) .setDefaultCredentialsProvider(credsProvider) .setSSLSocketFactory(csf) .build(); } catch (IOException | UnrecoverableKeyException | CertificateException | NoSuchAlgorithmException | KeyStoreException | NoSuchProviderException | KeyManagementException e) { throw new CannotInitializeDataAdapterException("Could not initialize adapter to source '" + this.getSourceName() + "': " + e.getMessage(), e); } }
public static void main(String[] args) throws Exception { System.setProperty("java.security.auth.login.config", ClientKerberosAuthentication.class.getResource("/jaas_login.conf").toExternalForm()); System.setProperty("sun.security.krb5.debug", "true"); System.setProperty("javax.security.auth.useSubjectCredsOnly", "false"); String targetUrl; if (args.length < 1) { throw new IllegalArgumentException("Please specify a target URL"); } targetUrl = args[0]; /* ***********************************************************************************************/ RegistryBuilder<AuthSchemeProvider> schemeProviderBuilder = RegistryBuilder.create(); schemeProviderBuilder.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new Credentials() { @Override public Principal getUserPrincipal() { System.out.print("Get principal!"); return null; } @Override public String getPassword() { System.out.print("Get pwd!"); return null; } }); CloseableHttpClient httpClient = HttpClients.custom() .setDefaultAuthSchemeRegistry(schemeProviderBuilder.build()) .setDefaultCredentialsProvider(credsProvider) .build(); doGet(httpClient, targetUrl); httpClient.close(); }
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"); } }
private HttpContext createSpnegoAwareHttpContext() { HttpClientContext httpContext = HttpClientContext.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true, useCanonicalHostname)).build(); httpContext.setAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullCredentials()); httpContext.setCredentialsProvider(credentialsProvider); return httpContext; }
private static HttpClient getHttpClient() { Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build(); return HttpClients.custom() .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credentialsProvider) .build(); }
public void testTokenAuthentication() { HttpClient client = new HttpClientConfigurator().host("bob").enableTokenAuthentication(true, null, null).getClient(); Registry<AuthSchemeProvider> registry = getAuthSchemeRegistry(client); assertThat(registry.lookup("bearer")).isInstanceOf(BearerSchemeFactory.class); RequestConfig defaultConfig = getDefaultConfig(client); assertThat(defaultConfig.getTargetPreferredAuthSchemes().size()).isEqualTo(1); assertThat(defaultConfig.getTargetPreferredAuthSchemes().iterator().next()).isEqualTo("Bearer"); }
@Override public AuthSchemeProvider lookup(final String name) { if (name.equalsIgnoreCase(HttpSignatureAuthScheme.SCHEME_NAME)) { return authSchemeProvider; } else { return null; } }
/** * Create a new instance of the {@code HttpClientMessageSender} with a default {@link HttpClient} * with added support for NTLM. * * @param ntlmUsername the NTLM username (without domain name) * @param ntlmPassword the NTLM password * @param ntlmDomain the NTLM domain */ public NtlmCloseableHttpComponentsMessageSender(String ntlmUsername, String ntlmPassword, String ntlmDomain) { super(); Assert.hasText(ntlmUsername, "the ntlmUsername must not be empty"); Assert.hasText(ntlmPassword, "the ntlmPassword must not be empty"); Assert.hasText(ntlmDomain, "the ntlmDomain must not be empty"); this.ntlmUsername = ntlmUsername; this.ntlmPassword = ntlmPassword; this.ntlmDomain = ntlmDomain; // Register NTLMSchemeFactory with the HttpClient instance you want to NTLM enable. Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .build(); getClientBuilder().setDefaultAuthSchemeRegistry(authSchemeRegistry); NTCredentials credentials = new NTCredentials(ntlmUsername, ntlmPassword, MACHINE_NAME, ntlmDomain); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); setCredentials(credentials); credentialsProvider.setCredentials(AuthScope.ANY, credentials); // register NTLM to HttpClient setCredentialsProvider(credentialsProvider); }
@Test public void buildLookupWithBasicAuth() { AuthSchemeProvider provider = getAuthSchemeProvider(AuthSchemes.BASIC); assertThat(provider, instanceOf(BasicSchemeFactory.class)); BasicScheme basicSchema = ((BasicScheme) provider.create(null)); assertEquals("UTF-8", basicSchema.getCredentialsCharset().toString()); }
@Test public void buildLookupWithKerberosAuth() { AuthTypes authTypes = new AuthTypes(AuthSchemes.KERBEROS); AuthSchemeProvider provider = new AuthSchemeProviderLookupBuilder() .setAuthTypes(authTypes) .setHost("myweb.contoso.com").buildAuthSchemeProviderLookup().lookup(AuthSchemes.KERBEROS); assertThat(provider, instanceOf(KerberosSchemeFactory.class)); }
private AuthSchemeProvider getAuthSchemeProvider(String authType) { AuthTypes authTypes = new AuthTypes(authType); Lookup<AuthSchemeProvider> lookup = new AuthSchemeProviderLookupBuilder() .setHeaders(new ArrayList<Header>()) .setAuthTypes(authTypes) .buildAuthSchemeProviderLookup(); return lookup.lookup(authType); }
private CloseableHttpClient buildHttpClient(HttpHost proxy) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(ANY, noCredentials()); Registry<AuthSchemeProvider> registry = RegistryBuilder.<AuthSchemeProvider> create().register(NTLM, new NTLMSchemeProvider()).build(); RequestConfig requestConfig = RequestConfig.custom().setProxyPreferredAuthSchemes(singleton(NTLM)).build(); return HttpClients.custom().setDefaultRequestConfig(requestConfig).setRoutePlanner(new DefaultProxyRoutePlanner(proxy)).setDefaultAuthSchemeRegistry(registry) .setDefaultCredentialsProvider(credentialsProvider).disableRedirectHandling().build(); }
/** * @param listener Log listener * @param prompt Prompt for proxy credentials * @return Builder for HTTP client */ public HttpClientBuilder build(final TranscriptListener listener, final LoginCallback prompt) { final HttpClientBuilder configuration = HttpClients.custom(); // Use HTTP Connect proxy implementation provided here instead of // relying on internal proxy support in socket factory final Proxy proxy = proxyFinder.find(host); switch(proxy.getType()) { case HTTP: case HTTPS: final HttpHost h = new HttpHost(proxy.getHostname(), proxy.getPort(), StringUtils.lowerCase(proxy.getType().name())); if(log.isInfoEnabled()) { log.info(String.format("Setup proxy %s", h)); } configuration.setProxy(h); configuration.setProxyAuthenticationStrategy(new CallbackProxyAuthenticationStrategy(ProxyCredentialsStoreFactory.get(), host, prompt)); break; } configuration.setUserAgent(new PreferencesUseragentProvider().get()); final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000; configuration.setDefaultSocketConfig(SocketConfig.custom() .setTcpNoDelay(true) .setSoTimeout(timeout) .build()); configuration.setDefaultRequestConfig(this.createRequestConfig(timeout)); final String encoding; if(null == host.getEncoding()) { encoding = preferences.getProperty("browser.charset.encoding"); } else { encoding = host.getEncoding(); } configuration.setDefaultConnectionConfig(ConnectionConfig.custom() .setBufferSize(preferences.getInteger("http.socket.buffer")) .setCharset(Charset.forName(encoding)) .build()); if(preferences.getBoolean("http.connections.reuse")) { configuration.setConnectionReuseStrategy(new DefaultClientConnectionReuseStrategy()); } else { configuration.setConnectionReuseStrategy(new NoConnectionReuseStrategy()); } configuration.setRetryHandler(new ExtendedHttpRequestRetryHandler(preferences.getInteger("http.connections.retry"))); configuration.setServiceUnavailableRetryStrategy(new DisabledServiceUnavailableRetryStrategy()); if(!preferences.getBoolean("http.compression.enable")) { configuration.disableContentCompression(); } configuration.setRequestExecutor(new LoggingHttpRequestExecutor(listener)); // Always register HTTP for possible use with proxy. Contains a number of protocol properties such as the // default port and the socket factory to be used to create the java.net.Socket instances for the given protocol configuration.setConnectionManager(this.createConnectionManager(this.createRegistry())); configuration.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory( Charset.forName(preferences.getProperty("http.credentials.charset")))) .register(AuthSchemes.DIGEST, new DigestSchemeFactory( Charset.forName(preferences.getProperty("http.credentials.charset")))) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build()); return configuration; }
public Lookup<AuthSchemeProvider> getAuthSchemeRegistry() { return getLookup(AUTHSCHEME_REGISTRY, AuthSchemeProvider.class); }