public void upgrade( final ManagedHttpClientConnection conn, final HttpHost host, final HttpContext context) throws IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); } if (!(sf instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; Socket sock = conn.getSocket(); final int port = this.schemePortResolver.resolve(host); sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); conn.bind(sock); }
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; }
@Override public void upgrade( final ManagedHttpClientConnection conn, final HttpHost host, final HttpContext context) throws IOException { final HttpClientContext clientContext = HttpClientContext.adapt(context); final Lookup<ConnectionSocketFactory> registry = getSocketFactoryRegistry(clientContext); final ConnectionSocketFactory sf = registry.lookup(host.getSchemeName()); if (sf == null) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol is not supported"); } if (!(sf instanceof LayeredConnectionSocketFactory)) { throw new UnsupportedSchemeException(host.getSchemeName() + " protocol does not support connection upgrade"); } final LayeredConnectionSocketFactory lsf = (LayeredConnectionSocketFactory) sf; Socket sock = conn.getSocket(); final int port = this.schemePortResolver.resolve(host); sock = lsf.createLayeredSocket(sock, host.getHostName(), port, context); conn.bind(sock); }
@SuppressWarnings("unchecked") @Before public void setup() throws Exception { execChain = Mockito.mock(ClientExecChain.class); connManager = Mockito.mock(HttpClientConnectionManager.class); routePlanner = Mockito.mock(HttpRoutePlanner.class); cookieSpecRegistry = Mockito.mock(Lookup.class); authSchemeRegistry = Mockito.mock(Lookup.class); cookieStore = Mockito.mock(CookieStore.class); credentialsProvider = Mockito.mock(CredentialsProvider.class); defaultConfig = RequestConfig.custom().build(); closeable1 = Mockito.mock(Closeable.class); closeable2 = Mockito.mock(Closeable.class); client = new InternalHttpClient(execChain, connManager, routePlanner, cookieSpecRegistry, authSchemeRegistry, cookieStore, credentialsProvider, defaultConfig, Arrays.asList(closeable1, closeable2)); }
@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()); }
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; }
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; }
HttpClientConnectionOperator( final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); Args.notNull(socketFactoryRegistry, "Socket factory registry"); this.socketFactoryRegistry = socketFactoryRegistry; this.schemePortResolver = schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE; this.dnsResolver = dnsResolver != null ? dnsResolver : SystemDefaultDnsResolver.INSTANCE; }
@SuppressWarnings("unchecked") private Lookup<ConnectionSocketFactory> getSocketFactoryRegistry(final HttpContext context) { Lookup<ConnectionSocketFactory> reg = (Lookup<ConnectionSocketFactory>) context.getAttribute( SOCKET_FACTORY_REGISTRY); if (reg == null) { reg = this.socketFactoryRegistry; } return reg; }
public BasicHttpClientConnectionManager( final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); this.connectionOperator = new HttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); this.connFactory = connFactory != null ? connFactory : ManagedHttpClientConnectionFactory.INSTANCE; this.expiry = Long.MAX_VALUE; this.socketConfig = SocketConfig.DEFAULT; this.connConfig = ConnectionConfig.DEFAULT; this.isShutdown = new AtomicBoolean(false); }
PoolingHttpClientConnectionManager( final CPool pool, final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); this.configData = new ConfigData(); this.pool = pool; this.connectionOperator = new HttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); this.isShutDown = new AtomicBoolean(false); }
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); } }
/** * @since 4.5 */ public ResponseContentEncoding(final Lookup<InputStreamFactory> decoderRegistry, final boolean ignoreUnknown) { this.decoderRegistry = decoderRegistry != null ? decoderRegistry : RegistryBuilder.<InputStreamFactory>create() .register("gzip", GZIP) .register("x-gzip", GZIP) .register("deflate", DEFLATE) .build(); this.ignoreUnknown = ignoreUnknown; }
@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; }
public BasicHttpClientConnectionManager( final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { this( new DefaultHttpClientConnectionOperator(socketFactoryRegistry, schemePortResolver, dnsResolver), connFactory ); }
/** * Visible for test. */ PoolingHttpClientConnectionManager( final CPool pool, final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); this.configData = new ConfigData(); this.pool = pool; this.connectionOperator = new DefaultHttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); this.isShutDown = new AtomicBoolean(false); }
public DefaultHttpClientConnectionOperator( final Lookup<ConnectionSocketFactory> socketFactoryRegistry, final SchemePortResolver schemePortResolver, final DnsResolver dnsResolver) { super(); Args.notNull(socketFactoryRegistry, "Socket factory registry"); this.socketFactoryRegistry = socketFactoryRegistry; this.schemePortResolver = schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE; this.dnsResolver = dnsResolver != null ? dnsResolver : SystemDefaultDnsResolver.INSTANCE; }
@SuppressWarnings("unchecked") @Before public void setup() throws Exception { conn = Mockito.mock(ManagedHttpClientConnection.class); socket = Mockito.mock(Socket.class); plainSocketFactory = Mockito.mock(ConnectionSocketFactory.class); sslSocketFactory = Mockito.mock(LayeredConnectionSocketFactory.class); socketFactoryRegistry = Mockito.mock(Lookup.class); schemePortResolver = Mockito.mock(SchemePortResolver.class); dnsResolver = Mockito.mock(DnsResolver.class); connectionOperator = new DefaultHttpClientConnectionOperator( socketFactoryRegistry, schemePortResolver, dnsResolver); }
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; }
@Test public void newConnectionManagerWithSSL() throws Exception { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() .newConnectionManager(false, 2, 6); Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup( connectionManager); assertThat(socketFactoryRegistry.lookup("https"), is(notNullValue())); assertThat(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers(), is(notNullValue())); }
@Test public void newConnectionManagerWithDisabledSSLValidation() throws Exception { HttpClientConnectionManager connectionManager = new DefaultApacheHttpClientConnectionManagerFactory() .newConnectionManager(true, 2, 6); Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup( connectionManager); assertThat(socketFactoryRegistry.lookup("https"), is(notNullValue())); assertThat(getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers(), is(nullValue())); }
private X509TrustManager getX509TrustManager( Lookup<ConnectionSocketFactory> socketFactoryRegistry) { ConnectionSocketFactory connectionSocketFactory = socketFactoryRegistry .lookup("https"); SSLSocketFactory sslSocketFactory = getField(connectionSocketFactory, "socketfactory"); SSLContextSpi sslContext = getField(sslSocketFactory, "context"); return getField(sslContext, "trustManager"); }
@Test public void disableSslTest() throws Exception { HttpClientConnectionManager connectionManager = context.getBean(HttpClientConnectionManager.class); Lookup<ConnectionSocketFactory> socketFactoryRegistry = getConnectionSocketFactoryLookup(connectionManager); assertNotNull(socketFactoryRegistry.lookup("https")); assertNull(this.getX509TrustManager(socketFactoryRegistry).getAcceptedIssuers()); }
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); }