List of usage examples for org.apache.http.client.config AuthSchemes DIGEST
String DIGEST
To view the source code for org.apache.http.client.config AuthSchemes DIGEST.
Click Source Link
From source file:org.wildfly.core.test.standalone.mgmt.api.core.ResponseAttachmentTestCase.java
private CloseableHttpClient createHttpClient(URL url) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(/*from w w w . j a va 2s .c o m*/ new AuthScope(url.getHost(), url.getPort(), "ManagementRealm", AuthSchemes.DIGEST), new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD)); return HttpClientBuilder.create().setDefaultCredentialsProvider(credsProvider).build(); }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Set the builder based on the request elements * // w w w . j av a2 s.c o m * @param requestConfigurationBuilder The builder to be set * @param authorization The authentication element of the request * @param proxy The proxy element of the request * @param urlHost The URL host of the request * @param urlPort The URL post of the request * @param urlProtocol The URL protocol of the request * @param httpClientBuilder The builder to be set * @return HTTPContext The HTTP context to be set */ private HttpContext setAuthorizations(final Builder requestConfigurationBuilder, final Authorization authorization, final Proxy proxy, final String urlHost, final int urlPort, final String urlProtocol, final HttpClientBuilder httpClientBuilder) { HttpContext httpContext = HttpClientContext.create(); if (authorization != null) { if (authorization instanceof BasicDigestAuthorization) { final BasicDigestAuthorization castAuthorization = (BasicDigestAuthorization) authorization; final List<String> authPrefs = new ArrayList<>(); if (castAuthorization.isBasic()) { authPrefs.add(AuthSchemes.BASIC); } else { authPrefs.add(AuthSchemes.DIGEST); } requestConfigurationBuilder.setTargetPreferredAuthSchemes(authPrefs); final String username = castAuthorization.getUsername(); final String password = new String(castAuthorization.getPassword()); String host = urlHost; if (isStringInputValid(castAuthorization.getHost())) { host = castAuthorization.getHost(); } int port = urlPort; if (castAuthorization.getPort() != null) { port = castAuthorization.getPort(); } String realm = AuthScope.ANY_REALM; if (isStringInputValid(castAuthorization.getRealm())) { realm = castAuthorization.getRealm(); } final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host, port, realm), new UsernamePasswordCredentials(username, password)); setProxyCrendentials(proxy, credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); if (castAuthorization.isPreemptive() || proxy != null) { final AuthCache authoriationCache = new BasicAuthCache(); if (castAuthorization.isPreemptive()) { AuthSchemeBase authorizationScheme = null; if (castAuthorization.isBasic()) { authorizationScheme = new BasicScheme(ChallengeState.TARGET); } else { authorizationScheme = new DigestScheme(ChallengeState.TARGET); } authoriationCache.put(new HttpHost(host, port, urlProtocol), authorizationScheme); } if (proxy != null) { final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY); authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme); } final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authoriationCache); httpContext = localContext; } } } else if (proxy != null) { final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); setProxyCrendentials(proxy, credentialsProvider); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); // Make it preemptive if (proxy.hasCredentials()) { final AuthCache authoriationCache = new BasicAuthCache(); final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY); authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme); final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authoriationCache); httpContext = localContext; } } return httpContext; }
From source file:net.yacy.cora.protocol.http.HTTPClient.java
/** * Send data using HTTP POST method to the server named by vhost * * @param url address to request on the server * @param vhost name of the server at address which should respond. When null, localhost is assumed. * @param post data to send (name-value-pairs) * @param userName user name for HTTP authentication : only sent when requesting localhost * @param password encoded password for HTTP authentication : only sent when requesting localhost * @param usegzip if the body should be gzipped * @return response body//from ww w . j a v a2 s . co m * @throws IOException when an error occurred */ public byte[] POSTbytes(final MultiProtocolURL url, final String vhost, final Map<String, ContentBody> post, final String userName, final String password, final boolean usegzip, final boolean concurrent) throws IOException { final HttpPost httpPost = new HttpPost(url.toNormalform(true)); final boolean localhost = Domains.isLocalhost(url.getHost()); if (!localhost) setHost(url.getHost()); // overwrite resolved IP, needed for shared web hosting DO NOT REMOVE, see http://en.wikipedia.org/wiki/Shared_web_hosting_service if (vhost == null) setHost(Domains.LOCALHOST); final MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create(); for (final Entry<String, ContentBody> part : post.entrySet()) entityBuilder.addPart(part.getKey(), part.getValue()); final HttpEntity multipartEntity = entityBuilder.build(); // statistics this.upbytes = multipartEntity.getContentLength(); if (usegzip) { httpPost.setEntity(new GzipCompressingEntity(multipartEntity)); } else { httpPost.setEntity(multipartEntity); } if (!localhost || password == null) { return getContentBytes(httpPost, Integer.MAX_VALUE, concurrent); } byte[] content = null; final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", url.getPort()), new UsernamePasswordCredentials(userName, password)); /* Use the custom YaCyDigestScheme for HTTP Digest Authentication */ final Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new YaCyDigestSchemeFactory()).build(); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider) .setDefaultAuthSchemeRegistry(authSchemeRegistry).build(); try { this.httpResponse = httpclient.execute(httpPost); try { HttpEntity httpEntity = this.httpResponse.getEntity(); if (httpEntity != null) { if (getStatusCode() == HttpStatus.SC_OK) { content = getByteArray(httpEntity, Integer.MAX_VALUE); } // Ensures that the entity content is fully consumed and the content stream, if exists, is closed. EntityUtils.consume(httpEntity); } } finally { this.httpResponse.close(); } } finally { httpclient.close(); } return content; }
From source file:com.mirth.connect.connectors.http.HttpDispatcher.java
private void processDigestChallenge(AuthCache authCache, HttpHost target, Credentials credentials, HttpRequest request, HttpContext context) throws AuthenticationException { Header authHeader = request.getFirstHeader("Authorization"); /*/*from w w w.j a v a2 s.c o m*/ * Since we're going to be replacing the header, we remove it here. If the header is invalid * or the challenge fails, we still want to remove the header, because otherwise it will * interfere with reactive authentication. */ request.removeHeaders("Authorization"); if (authHeader != null) { String authValue = authHeader.getValue(); // The Authorization header value will be in the form: Digest param1="value1", param2="value2" if (StringUtils.startsWithIgnoreCase(authValue, AuthSchemes.DIGEST)) { DigestScheme digestScheme = new DigestScheme(); // Get the actual parameters by stripping off the "Digest" authValue = StringUtils.removeStartIgnoreCase(authValue, AuthSchemes.DIGEST).trim(); Matcher matcher = AUTH_HEADER_PATTERN.matcher(authValue); while (matcher.find()) { // We found a param="value" group String group = matcher.group(); int index = group.indexOf('='); String name = group.substring(0, index).trim(); String value = group.substring(index + 1).trim(); // Strip off any quotes in the value if (value.startsWith("\"")) { value = value.substring(1); } if (value.endsWith("\"")) { value = value.substring(0, value.length() - 1); } logger.debug("Overriding Digest Parameter: " + name + "=\"" + value + "\""); digestScheme.overrideParamter(name, value); } // Since this is preemptive, we need to actually process the challenge beforehand request.addHeader(digestScheme.authenticate(credentials, request, context)); authCache.put(target, digestScheme); } } }
From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java
protected boolean isCachable(final AuthScheme authScheme) { if (authScheme == null || !authScheme.isComplete()) { return false; }/*from w w w . ja v a2 s . co m*/ final String schemeName = authScheme.getSchemeName(); return schemeName.equalsIgnoreCase(AuthSchemes.BASIC) || schemeName.equalsIgnoreCase(AuthSchemes.DIGEST); }
From source file:org.jboss.as.test.integration.security.common.Utils.java
/** * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and username is provided, then a new * request is created with the provided credentials (basic authentication). * * @param url URL to which the request should be made * @param user Username (may be null)//from ww w. j a v a 2 s. co m * @param pass Password (may be null) * @param expectedStatusCode expected status code returned from the requested server * @param checkFollowupAuthState whether to check auth state for followup request - if set to true, followup * request is sent to server and 200 OK is expected directly (no re-authentication * challenge - 401 Unauthorized - is expected) * @return HTTP response body * @throws IOException * @throws URISyntaxException */ public static String makeCallWithBasicAuthn(URL url, String user, String pass, int expectedStatusCode, boolean checkFollowupAuthState) throws IOException, URISyntaxException { LOGGER.trace("Requesting URL " + url); // use UTF-8 charset for credentials Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory(Consts.UTF_8)) .register(AuthSchemes.DIGEST, new DigestSchemeFactory(Consts.UTF_8)).build(); try (final CloseableHttpClient httpClient = HttpClientBuilder.create() .setDefaultAuthSchemeRegistry(authSchemeRegistry).build()) { final HttpGet httpGet = new HttpGet(url.toURI()); HttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) { assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode); return EntityUtils.toString(response.getEntity()); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user); } HttpEntity entity = response.getEntity(); if (entity != null) EntityUtils.consume(entity); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, pass); HttpClientContext hc = new HttpClientContext(); hc.setCredentialsProvider(new BasicCredentialsProvider()); hc.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()), credentials); //enable auth response = httpClient.execute(httpGet, hc); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode); if (checkFollowupAuthState) { // Let's disable authentication for this client as we already have all the context neccessary to be // authorized (we expect that gained 'nonce' value can be re-used in our case here). // By disabling authentication we simply get first server response and thus we can check whether we've // got 200 OK or different response code. RequestConfig reqConf = RequestConfig.custom().setAuthenticationEnabled(false).build(); httpGet.setConfig(reqConf); response = httpClient.execute(httpGet, hc); statusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code returned after the authentication.", HttpURLConnection.HTTP_OK, statusCode); } return EntityUtils.toString(response.getEntity()); } }
From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Called from {@link #init(javax.servlet.ServletConfig)}. HttpClient offers * many opportunities for customization. By default, <a href= * "http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/SystemDefaultHttpClient.html"> * SystemDefaultHttpClient</a> is used if available, otherwise it falls back * to:/* w w w . j a v a 2s.c o m*/ * * <pre> * new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams) * </pre> * * SystemDefaultHttpClient uses PoolingClientConnectionManager. In any case, * it should be thread-safe. */ protected HttpClient createHttpClient(HttpParams hcParams) { try { String negotiateURL = getConfigParam("negotiate.url"); String negotiateSPN = getConfigParam("negotiate.spn"); if (negotiateURL != null && negotiateSPN != null) { System.out.println("negotiate url:" + negotiateURL); System.out.println("negotiate spn:" + negotiateSPN); // initialize the Windows security Context to get the negotiate // client token IWindowsSecurityContext clientContext = null; IWindowsCredentialsHandle clientCredentials = null; clientContext = WindowsSecurityContextImpl.getCurrent(SECURITY_PACKAGE, negotiateSPN); clientCredentials = WindowsCredentialsHandleImpl.getCurrent(SECURITY_PACKAGE); clientCredentials.initialize(); String username = WindowsAccountImpl.getCurrentUsername(); System.out.println("credentials for user " + username + " get prepared"); byte[] token = clientContext.getToken(); // encode the token with Base64 to be able to add it to the http // header String clientToken = Base64.encodeBase64String(token); System.out.println("clientToken" + clientToken); // if there is only a negotiate url the rest of the // authorization is based on cookies // so we need to support them. CookieStore cookieStore = new BasicCookieStore(); RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); HttpClientContext context = HttpClientContext.create(); proxyContext = context; context.setCookieStore(cookieStore); HttpClient httpClient = HttpClients.custom().disableRedirectHandling() .setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore).build(); // first we need to act as a normal browser to get a http 401 // with negotiate header doActAsBrowser = true; HttpGet browserHttpGet = new HttpGet(negotiateURL); addBrowserHeader(browserHttpGet); HttpResponse rep = httpClient.execute(browserHttpGet, context); if (rep.getStatusLine().getStatusCode() == 401) { System.out.println("negotiate requested - sending negotiate client token"); HttpGet negotiateHttpGet = new HttpGet(negotiateURL); addBrowserHeader(negotiateHttpGet); negotiateHttpGet.addHeader("Authorization", "Negotiate " + clientToken); HttpResponse response = httpClient.execute(negotiateHttpGet, context); System.out.println( "http result code of negotiate request:" + response.getStatusLine().getStatusCode()); // now the url needs to be called periodically to keep the // cookie and connection alive String refreshTimeString = getConfigParam("negotiate.refreshtime"); long refreshTime = 1000000; if (refreshTimeString != null) { refreshTime = Long.parseLong(refreshTimeString); } HttpClientRefreshThread thread = new HttpClientRefreshThread(refreshTime, negotiateURL); thread.start(); List<org.apache.http.cookie.Cookie> cookies = context.getCookieStore().getCookies(); cookieString = ""; int size = cookies.size() - 1; for (int i = 0; i < cookies.size(); i++) { cookieString += cookies.get(i).getName(); cookieString += "="; cookieString += cookies.get(i).getValue(); if (i != size) cookieString += "; "; } } else { System.out.println("No negotiate requested"); } } else { if (!WinHttpClients.isWinAuthAvailable()) { System.out.println("Integrated Win auth is not supported!!!"); } else { HttpClientBuilder builder = WinHttpClients.custom(); Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); String username = getConfigParam("user"); String password = getConfigParam("password"); String domain = getConfigParam("domain"); String host = getConfigParam("host"); if (username != null) { NTCredentials cred = new NTCredentials(username, password, host, domain); CredentialsProvider credsProvider = new WindowsCredentialsProvider( new SystemDefaultCredentialsProvider()); credsProvider.setCredentials(AuthScope.ANY, cred); builder.setDefaultCredentialsProvider(credsProvider); } builder.disableCookieManagement(); builder.disableRedirectHandling(); return builder.build(); } // as of HttpComponents v4.2, this class is better since it uses // System // Properties: Class<?> clientClazz = Class.forName("org.apache.http.impl.client.SystemDefaultHttpClient"); Constructor<?> constructor = clientClazz.getConstructor(HttpParams.class); return (HttpClient) constructor.newInstance(hcParams); } } catch (ClassNotFoundException e) { // no problem; use v4.1 below } catch (Exception e) { throw new RuntimeException(e); } // Fallback on using older client: return new DefaultHttpClient(new ThreadSafeClientConnManager(), hcParams); }