List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme
public BasicScheme()
From source file:org.dataconservancy.archive.impl.fcrepo.ri.MultiThreadedHttpClient.java
public MultiThreadedHttpClient(HttpClientConfig config) { this.config = config; if (config.getPreemptiveAuthN()) { HttpRequestInterceptor interceptor = new HttpRequestInterceptor() { @Override/*from ww w. ja v a 2 s . c o m*/ public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If no auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; addRequestInterceptor(interceptor, 0); } }
From source file:org.opennms.minion.core.impl.ScvEnabledRestClientImpl.java
@Override public void ping() throws Exception { // Setup a client with pre-emptive authentication HttpHost target = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(username, password)); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try {/*from ww w . ja v a 2s . c o m*/ AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); // Issue a simple GET against the Info endpoint HttpGet httpget = new HttpGet(url.toExternalForm() + "/rest/info"); CloseableHttpResponse response = httpclient.execute(target, httpget, localContext); response.close(); } finally { httpclient.close(); } }
From source file:com.gsma.mobileconnect.utils.RestClient.java
/** * Build a HttpClientContext that will preemptively authenticate using Basic Authentication * * @param username Username for credentials * @param password Password for credentials * @param uriForRealm uri used to determine the authentication realm * @return A HttpClientContext that will preemptively authenticate using Basic Authentication *///w ww . j a v a 2s . co m public HttpClientContext getHttpClientContext(String username, String password, URI uriForRealm) { String host = URIUtils.extractHost(uriForRealm).getHostName(); int port = uriForRealm.getPort(); if (port == -1) { if (Constants.HTTP_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) { port = Constants.HTTP_PORT; } else if (Constants.HTTPS_SCHEME.equalsIgnoreCase(uriForRealm.getScheme())) { port = Constants.HTTPS_PORT; } } CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(host, port, uriForRealm.getScheme()), new BasicScheme()); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credentialsProvider); context.setAuthCache(authCache); return context; }
From source file:org.apache.cloudstack.cloudian.client.CloudianClient.java
public CloudianClient(final String host, final Integer port, final String scheme, final String username, final String password, final boolean validateSSlCertificate, final int timeout) throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException { final CredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); final HttpHost adminHost = new HttpHost(host, port, scheme); final AuthCache authCache = new BasicAuthCache(); authCache.put(adminHost, new BasicScheme()); this.adminApiUrl = adminHost.toURI(); this.httpContext = HttpClientContext.create(); this.httpContext.setCredentialsProvider(provider); this.httpContext.setAuthCache(authCache); final RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout * 1000) .setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build(); if (!validateSSlCertificate) { final SSLContext sslcontext = SSLUtils.getSSLContext(); sslcontext.init(null, new X509TrustManager[] { new TrustAllManager() }, new SecureRandom()); final SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext, NoopHostnameVerifier.INSTANCE); this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider) .setDefaultRequestConfig(config).setSSLSocketFactory(factory).build(); } else {//from ww w .j a va 2s.c o m this.httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider) .setDefaultRequestConfig(config).build(); } }
From source file:org.pentaho.di.core.util.HttpClientUtil.java
/** * Returns context with AuthCache or null in case of any exception was thrown. * * @param host/*from w w w . j a v a2s .c o m*/ * @param port * @param user * @param password * @param schema * @return {@link org.apache.http.client.protocol.HttpClientContext HttpClientContext} */ public static HttpClientContext createPreemptiveBasicAuthentication(String host, int port, String user, String password, String schema) { HttpClientContext localContext = null; try { HttpHost target = new HttpHost(host, port, schema); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(user, password)); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local // auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(target, basicAuth); // Add AuthCache to the execution context localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); } catch (Exception e) { return null; } return localContext; }
From source file:com.garyclayburg.scimclient.authn.AuthHttpComponentsClientHttpRequestFactory.java
@Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(host, basicAuth);// ww w . j a va2 s . c o m // Add AuthCache to the execution context HttpClientContext localcontext = HttpClientContext.create(); localcontext.setAuthCache(authCache); if (userName != null) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(userName, password)); localcontext.setCredentialsProvider(credsProvider); } return localcontext; }
From source file:org.hawkular.client.core.jaxrs.RestFactory.java
public T createAPI(ClientInfo clientInfo) { final HttpClient httpclient; if (clientInfo.getEndpointUri().toString().startsWith("https")) { httpclient = getHttpClient();// w w w.j a va2 s . co m } else { httpclient = HttpClientBuilder.create().build(); } final ResteasyClient client; if (clientInfo.getUsername().isPresent() && clientInfo.getPassword().isPresent()) { HttpHost targetHost = new HttpHost(clientInfo.getEndpointUri().getHost(), clientInfo.getEndpointUri().getPort()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(clientInfo.getUsername().get(), clientInfo.getPassword().get())); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setAuthCache(authCache); ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpclient, context); client = new ResteasyClientBuilder().httpEngine(engine).build(); } else { ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(getHttpClient()); client = new ResteasyClientBuilder().httpEngine(engine).build(); } client.register(JacksonJaxbJsonProvider.class); client.register(JacksonObjectMapperProvider.class); client.register(RequestLoggingFilter.class); client.register(new RequestHeadersFilter(clientInfo.getHeaders())); client.register(ResponseLoggingFilter.class); client.register(HCJacksonJson2Provider.class); client.register(ConvertersProvider.class); ProxyBuilder<T> proxyBuilder = client.target(clientInfo.getEndpointUri()).proxyBuilder(apiClassType); if (classLoader != null) { proxyBuilder = proxyBuilder.classloader(classLoader); } return proxyBuilder.build(); }
From source file:ua.pp.msk.gradle.http.Client.java
private void init(URL targetURL, String user, String password) throws ClientSslException { this.targetUrl = targetURL; logger.debug("Initializing " + this.getClass().getName() + " with target URL " + targetURL.toString()); HttpHost htHost = new HttpHost(targetUrl.getHost(), targetUrl.getPort(), targetUrl.getProtocol()); AuthCache aCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); aCache.put(htHost, basicAuth);/*www .ja va 2s .co m*/ UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password); BasicCredentialsProvider cProvider = new BasicCredentialsProvider(); cProvider.setCredentials(new AuthScope(htHost), creds); logger.debug("Credential provider: " + cProvider.toString()); context = new BasicHttpContext(); ClientContextConfigurer cliCon = new ClientContextConfigurer(context); cliCon.setCredentialsProvider(cProvider); context.setAttribute(ClientContext.AUTH_CACHE, aCache); SSLSocketFactory sslConnectionSocketFactory = null; try { sslConnectionSocketFactory = new SSLSocketFactory(new TrustSelfSignedStrategy(), new NexusHostnameVerifier()); } catch (KeyManagementException ex) { logger.error("Cannot manage secure keys", ex); throw new ClientSslException("Cannot manage secure keys", ex); } catch (KeyStoreException ex) { logger.error("Cannot build SSL context due to KeyStore error", ex); throw new ClientSslException("Cannot build SSL context due to KeyStore error", ex); } catch (NoSuchAlgorithmException ex) { logger.error("Unsupported security algorithm", ex); throw new ClientSslException("Unsupported security algorithm", ex); } catch (UnrecoverableKeyException ex) { logger.error("Unrecoverable key", ex); throw new ClientSslException("Unrecoverrable key", ex); } DefaultHttpClient defClient = new DefaultHttpClient(); defClient.setRedirectStrategy(new NexusRedirectStrategy()); defClient.setCredentialsProvider(cProvider); Scheme https = new Scheme("https", 443, sslConnectionSocketFactory); defClient.getConnectionManager().getSchemeRegistry().register(https); defClient.setTargetAuthenticationStrategy(new TargetAuthenticationStrategy()); client = defClient; }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
@Test public void testCookieForStateFullClient() throws Exception { setAnonymousAccess(false);//from w ww . ja v a 2 s .co m TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI nexusBaseURI = new URI(url); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0"); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(), nexusBaseURI.getScheme()); httpClient.getCredentialsProvider().setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache); // stateful clients must login first, since other rest urls create no sessions String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login"; assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200)); // after login check content but make sure only cookie is used httpClient.getCredentialsProvider().clear(); HttpGet getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie not set", sessionCookie, notNullValue()); httpClient.getCookieStore().clear(); // remove cookies // do not set the cookie, expect failure HttpGet failedGetMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401)); // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail // with a 401 httpClient.getCookieStore().addCookie(sessionCookie); getMethod = new HttpGet(url); assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200)); }