private void useCredentials(CredentialsProvider credentialsProvider, String host, int port, Collection<? extends Authentication> authentications) { Credentials httpCredentials; for (Authentication authentication : authentications) { String scheme = getAuthScheme(authentication); PasswordCredentials credentials = getPasswordCredentials(authentication); if (authentication instanceof AllSchemesAuthentication) { NTLMCredentials ntlmCredentials = new NTLMCredentials(credentials); httpCredentials = new NTCredentials(ntlmCredentials.getUsername(), ntlmCredentials.getPassword(), ntlmCredentials.getWorkstation(), ntlmCredentials.getDomain()); credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, AuthSchemes.NTLM), httpCredentials); LOGGER.debug("Using {} and {} for authenticating against '{}:{}' using {}", credentials, ntlmCredentials, host, port, AuthSchemes.NTLM); } httpCredentials = new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword()); credentialsProvider.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM, scheme), httpCredentials); LOGGER.debug("Using {} for authenticating against '{}:{}' using {}", credentials, host, port, scheme); } }
@Test public void request_has_proxy_config_when_proxy_auth_enabled() throws Exception { List<ProxyAuthenticationMethod> authMethods = Arrays.asList(ProxyAuthenticationMethod.BASIC, ProxyAuthenticationMethod.DIGEST, ProxyAuthenticationMethod.KERBEROS, ProxyAuthenticationMethod.NTLM, ProxyAuthenticationMethod.SPNEGO); List<String> expectedAuthMethods = Arrays.asList(AuthSchemes.BASIC, AuthSchemes.DIGEST, AuthSchemes.KERBEROS, AuthSchemes.NTLM, AuthSchemes.SPNEGO); ClientConfiguration configuration = new ClientConfiguration().withProxyHost("localhost") .withProxyPort(80) .withProxyUsername("user") .withProxyPassword("password") .withProxyAuthenticationMethods(authMethods); HttpClientSettings settings = HttpClientSettings.adapt(configuration); HttpRequestBase requestBase = requestFactory.create(newDefaultRequest(HttpMethodName.POST), settings); Assert.assertEquals(expectedAuthMethods, requestBase.getConfig().getProxyPreferredAuthSchemes()); }
@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(); }
/** * @since 4.3 */ public ProxyClient( final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final ConnectionConfig connectionConfig, final RequestConfig requestConfig) { super(); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT; this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT; this.httpProcessor = new ImmutableHttpProcessor( new RequestTargetHostHC4(), new RequestClientConnControl(), new RequestUserAgentHC4()); this.requestExec = new HttpRequestExecutor(); this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); this.authenticator = new HttpAuthenticator(); this.proxyAuthState = new AuthStateHC4(); this.authSchemeRegistry = new AuthSchemeRegistry(); this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactoryHC4()); this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactoryHC4()); this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory()); this.reuseStrategy = new DefaultConnectionReuseStrategyHC4(); }
/** * Configure credentials and auth scheme on client if an authorization is * available for url * @param client {@link HttpClient} * @param url URL to test * @param credentialsProvider {@link CredentialsProvider} * @param localHost host running JMeter */ public void setupCredentials(HttpClient client, URL url, CredentialsProvider credentialsProvider, String localHost) { Authorization auth = getAuthForURL(url); if (auth != null) { String username = auth.getUser(); String realm = auth.getRealm(); String domain = auth.getDomain(); if (log.isDebugEnabled()){ log.debug(username + " > D="+domain+" R="+realm + " M="+auth.getMechanism()); } if (Mechanism.KERBEROS.equals(auth.getMechanism())) { ((AbstractHttpClient) client).getAuthSchemes().register( AuthSchemes.SPNEGO, new FixedSPNegoSchemeFactory(isStripPort(url))); credentialsProvider.setCredentials(new AuthScope(null, -1, null), USE_JAAS_CREDENTIALS); } else { credentialsProvider.setCredentials( new AuthScope(url.getHost(), url.getPort(), realm.length()==0 ? null : realm), new NTCredentials(username, auth.getPass(), localHost, domain)); } } }
/** * @since 4.3 */ public ProxyClient( final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final ConnectionConfig connectionConfig, final RequestConfig requestConfig) { super(); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.connectionConfig = connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT; this.requestConfig = requestConfig != null ? requestConfig : RequestConfig.DEFAULT; this.httpProcessor = new ImmutableHttpProcessor( new RequestTargetHost(), new RequestClientConnControl(), new RequestUserAgent()); this.requestExec = new HttpRequestExecutor(); this.proxyAuthStrategy = new ProxyAuthenticationStrategy(); this.authenticator = new HttpAuthenticator(); this.proxyAuthState = new AuthState(); this.authSchemeRegistry = new AuthSchemeRegistry(); this.authSchemeRegistry.register(AuthSchemes.BASIC, new BasicSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.DIGEST, new DigestSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.NTLM, new NTLMSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()); this.authSchemeRegistry.register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()); this.reuseStrategy = new DefaultConnectionReuseStrategy(); }
/** * 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()); }
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(); } }
@Before @Override public void setUp() throws Exception { super.setUp(); this.serverBootstrap.registerHandler("/", new HttpRequestHandler() { @Override public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { response.addHeader(AUTH.WWW_AUTH, AuthSchemes.SPNEGO); response.setStatusCode(HttpStatus.SC_UNAUTHORIZED); } }); }
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; }
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()); }
private void doRequest(URL url) { WinRmClientBuilder builder = WinRmClient.builder(url); builder.authenticationScheme(AuthSchemes.BASIC); WinRmClient client = builder.build(); StringWriter out = new StringWriter(); StringWriter err = new StringWriter(); int code; try (ShellCommand shell = client.createShell()) { code = shell.execute("echo myline", out, err); } assertEquals(out.toString(), "myline\r\n"); assertEquals(err.toString(), ""); assertEquals(code, 0); }
@Bean @ConditionalOnMissingBean(HttpClient.class) public HttpClient httpClient(){ HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(30000) .setConnectTimeout(30000) .setTargetPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)) .setProxyPreferredAuthSchemes(ImmutableList.of(AuthSchemes.BASIC)) .build(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, getUsernamePasswordCredentials()); return HttpClients.custom().setConnectionManager(cm) .setDefaultCredentialsProvider(credentialsProvider) .setDefaultRequestConfig(requestConfig) .build(); }
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; }
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) { SSLContext sslContext = org.apache.http.ssl.SSLContexts.createDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslConnectionSocketFactory) .build(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); return HttpClientBuilder.create() .setConnectionManager(new PoolingHttpClientConnectionManager(registry)) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultCredentialsProvider(credentialsProvider) .build(); }
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) { try { SSLContext sslContext = SSLContexts.createDefault(); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionSocketFactory) .register("http", PlainConnectionSocketFactory.getSocketFactory()) .build(); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST), new UsernamePasswordCredentials(username, password)); PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry); HttpClientBuilder.create().setConnectionManager(connectionPool).build(); return HttpClientBuilder.create() .setConnectionManager(connectionPool) .setRetryHandler(new StandardHttpRequestRetryHandler(5, true)) .setDefaultCredentialsProvider(credsProvider).build(); } catch (Exception e) { throw new RuntimeException(e); } }
private void configureAuthSchemeRegistry(HttpClientBuilder builder) { builder.setDefaultAuthSchemeRegistry(RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()) .build() ); }
private String getAuthScheme(Authentication authentication) { if (authentication instanceof BasicAuthentication) { return AuthSchemes.BASIC; } else if (authentication instanceof DigestAuthentication) { return AuthSchemes.DIGEST; } else if (authentication instanceof AllSchemesAuthentication) { return AuthScope.ANY_SCHEME; } else { throw new IllegalArgumentException(String.format("Authentication scheme of '%s' is not supported.", authentication.getClass().getSimpleName())); } }
/** * 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); }
/** * Convert the customer-facing authentication method into an apache-specific authentication method. */ private String toApacheAuthenticationScheme(ProxyAuthenticationMethod authenticationMethod) { if (authenticationMethod == null) { throw new IllegalStateException("The configured proxy authentication methods must not be null."); } switch (authenticationMethod) { case NTLM: return AuthSchemes.NTLM; case BASIC: return AuthSchemes.BASIC; case DIGEST: return AuthSchemes.DIGEST; case SPNEGO: return AuthSchemes.SPNEGO; case KERBEROS: return AuthSchemes.KERBEROS; default: throw new IllegalStateException("Unknown authentication scheme: " + authenticationMethod); } }
/** * 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(); }
protected boolean isCachable(final AuthScheme authScheme) { if (authScheme == null || !authScheme.isComplete()) { return false; } final String schemeName = authScheme.getSchemeName(); return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) || schemeName.equalsIgnoreCase(AuthSchemes.DIGEST); }
public Credentials getCredentials(final AuthScope authscope) { Args.notNull(authscope, "Auth scope"); final Credentials localcreds = internal.getCredentials(authscope); if (localcreds != null) { return localcreds; } if (authscope.getHost() != null) { PasswordAuthentication systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.SERVER); if (systemcreds == null) { systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.PROXY); } if (systemcreds != null) { final String domain = System.getProperty("http.auth.ntlm.domain"); if (domain != null) { return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, domain); } else { if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) { // Domian may be specified in a fully qualified user name return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, null); } else { return new UsernamePasswordCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword())); } } } } return null; }
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); } }
public RawClient(@NotNull final Config config, @Nullable ConnectionService connectionService) { this.config = config; this.connectionService = connectionService; HttpClientBuilder httpBuilder = HttpClientBuilder.create(); requestConfigBuilder = RequestConfig.custom(); CredentialsProvider provider = new BasicCredentialsProvider(); String buildVersion = null; try { Properties buildProperties = new Properties(); InputStream in = getClass().getResourceAsStream("/com/samebug/clients/http/build.properties"); buildProperties.load(in); in.close(); buildVersion = buildProperties.getProperty("version"); } catch (Exception ignored) { } final String myUserAgent = buildVersion != null ? "Samebug-HttpClient/" + buildVersion : "Samebug-HttpClient"; requestConfigBuilder.setConnectTimeout(config.connectTimeout).setSocketTimeout(config.requestTimeout).setConnectionRequestTimeout(500); final ProxyConfig proxySettings = config.proxy; if (proxySettings != null && proxySettings.host != null && !proxySettings.host.isEmpty()) { requestConfigBuilder.setProxy(new HttpHost(proxySettings.host, proxySettings.port)); if (proxySettings.login != null && proxySettings.password != null) { provider.setCredentials(new AuthScope(proxySettings.host, proxySettings.port, AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(proxySettings.login, proxySettings.password, null, null)); provider.setCredentials(new AuthScope(proxySettings.host, proxySettings.port), new UsernamePasswordCredentials(proxySettings.login, proxySettings.password)); } } defaultRequestConfig = requestConfigBuilder.build(); trackingConfig = requestConfigBuilder.setSocketTimeout(TrackingRequestTimeout_Millis).build(); List<BasicHeader> defaultHeaders = new ArrayList<BasicHeader>(); defaultHeaders.add(new BasicHeader("User-Agent", config.appUserAgent + " " + myUserAgent)); httpClient = httpBuilder.setDefaultRequestConfig(defaultRequestConfig) .setMaxConnTotal(MaxConnections).setMaxConnPerRoute(MaxConnections) .setDefaultCredentialsProvider(provider) .setDefaultHeaders(defaultHeaders) .build(); }
/** * @deprecated To be removed in IDEA 16. Use corresponding method of IdeHttpClientHelpers. */ @Deprecated @NotNull public CredentialsProvider setProxyCredentials(@NotNull CredentialsProvider provider) { if (USE_HTTP_PROXY && PROXY_AUTHENTICATION) { String ntlmUserPassword = PROXY_LOGIN.replace('\\', '/') + ":" + getPlainProxyPassword(); provider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT, AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(ntlmUserPassword)); provider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(PROXY_LOGIN, getPlainProxyPassword())); } return provider; }
/** * Install credentials for IDE-wide proxy if usage of proxy and proxy authentication were enabled in {@link HttpConfigurable}. * * @param provider HttpClient's credentials provider used to configure new client * @see #setProxyCredentialsForUrlIfEnabled(CredentialsProvider, String) */ public static void setProxyCredentialsIfEnabled(@NotNull CredentialsProvider provider) { if (isHttpProxyEnabled() && isProxyAuthenticationEnabled()) { final String ntlmUserPassword = getProxyLogin().replace('\\', '/') + ":" + getProxyPassword(); provider.setCredentials(new AuthScope(getProxyHost(), getProxyPort(), AuthScope.ANY_REALM, AuthSchemes.NTLM), new NTCredentials(ntlmUserPassword)); provider.setCredentials(new AuthScope(getProxyHost(), getProxyPort()), new UsernamePasswordCredentials(getProxyLogin(), getProxyPassword())); } }
@Override public Credentials getCredentials(final AuthScope authscope) { Args.notNull(authscope, "Auth scope"); final Credentials localcreds = internal.getCredentials(authscope); if (localcreds != null) { return localcreds; } if (authscope.getHost() != null) { PasswordAuthentication systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.SERVER); if (systemcreds == null) { systemcreds = getSystemCreds( authscope, Authenticator.RequestorType.PROXY); } if (systemcreds != null) { final String domain = System.getProperty("http.auth.ntlm.domain"); if (domain != null) { return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, domain); } else { if (AuthSchemes.NTLM.equalsIgnoreCase(authscope.getScheme())) { // Domian may be specified in a fully qualified user name return new NTCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword()), null, null); } else { return new UsernamePasswordCredentials( systemcreds.getUserName(), new String(systemcreds.getPassword())); } } } } return null; }
/** * 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 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); }
@Override public Credentials getCredentials(final AuthScope authscope) { final String scheme = authscope.getScheme(); if (AuthSchemes.NTLM.equalsIgnoreCase(scheme) || AuthSchemes.SPNEGO.equalsIgnoreCase(scheme)) { return CurrentWindowsCredentials.INSTANCE; } else { return provider.getCredentials(authscope); } }
public WindowsNegotiateScheme(final String scheme, final String servicePrincipalName) { super(); this.scheme = (scheme == null) ? AuthSchemes.SPNEGO : scheme; this.challenge = null; this.continueNeeded = true; this.servicePrincipalName = servicePrincipalName; if (this.log.isDebugEnabled()) { this.log.debug("Created WindowsNegotiateScheme using " + this.scheme); } }
@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(); }