List of usage examples for org.apache.http.auth AuthScope ANY_REALM
String ANY_REALM
To view the source code for org.apache.http.auth AuthScope ANY_REALM.
Click Source Link
From source file:com.github.sardine.impl.SardineImpl.java
private CredentialsProvider getCredentialsProvider(String username, String password, String domain, String workstation) {//from ww w . ja va 2 s . com CredentialsProvider provider = new BasicCredentialsProvider(); if (username != null) { provider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM), new NTCredentials(username, password, workstation, domain)); provider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC), new UsernamePasswordCredentials(username, password)); provider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); provider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.SPNEGO), new UsernamePasswordCredentials(username, password)); provider.setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.KERBEROS), new UsernamePasswordCredentials(username, password)); } return provider; }
From source file:io.kahu.hawaii.util.call.http.HttpRequestBuilder.java
private void addAuthentication(AbortableHttpRequest<T> request, URI uri) { if (credentials != null) { CredentialsProvider credentialsProvider = null; switch (credentials.getAuthenticationType()) { case BASIC: // fall-through to default default:/*from w w w . j a v a2s .co m*/ BasicScheme authenticationScheme = new BasicScheme(); credentialsProvider = new BasicCredentialsProvider(); // Explicitly set the AuthScope to ANY_REALM in order to get // 'preemptive authentication' to work credentialsProvider.setCredentials( new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM, authenticationScheme.getSchemeName()), new UsernamePasswordCredentials(credentials.getUsername(), credentials.getPassword())); // Create an auth cache for preemptive authentication. AuthCache authCache = new BasicAuthCache(); authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), authenticationScheme); request.getHttpClientContext().setAuthCache(authCache); break; } request.getHttpClientContext().setCredentialsProvider(credentialsProvider); } }
From source file:org.eclipse.mylyn.commons.repositories.http.core.HttpUtil.java
public static void configureProxy(AbstractHttpClient client, RepositoryLocation location) { Assert.isNotNull(client);/*w w w . j av a 2 s. c o m*/ Assert.isNotNull(location); String url = location.getUrl(); Assert.isNotNull(url, "The location url must not be null"); //$NON-NLS-1$ String host = NetUtil.getHost(url); Proxy proxy; if (NetUtil.isUrlHttps(url)) { proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE); } else { proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE); } if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) { InetSocketAddress address = (InetSocketAddress) proxy.address(); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(address.getHostName(), address.getPort())); if (proxy instanceof AuthenticatedProxy) { AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy; Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(), address.getAddress(), false); if (credentials instanceof NTCredentials) { AuthScope proxyAuthScopeNTLM = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM, AuthPolicy.NTLM); client.getCredentialsProvider().setCredentials(proxyAuthScopeNTLM, credentials); AuthScope proxyAuthScopeAny = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM); Credentials usernamePasswordCredentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(), address.getAddress(), true); client.getCredentialsProvider().setCredentials(proxyAuthScopeAny, usernamePasswordCredentials); } else { AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(), AuthScope.ANY_REALM); client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials); } } } else { client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null); } }
From source file:com.googlecode.sardine.impl.SardineImpl.java
/** * @param username//from w w w . j a v a2 s. c o m * Use in authentication header credentials * @param password * Use in authentication header credentials * @param domain * NTLM authentication * @param workstation * NTLM authentication */ public void setCredentials(String username, String password, String domain, String workstation) { if (username != null) { this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.NTLM), new NTCredentials(username, password, workstation, domain)); this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.BASIC), new UsernamePasswordCredentials(username, password)); this.client.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM, AuthPolicy.DIGEST), new UsernamePasswordCredentials(username, password)); } }
From source file:org.artifactory.util.HttpClientConfigurator.java
/** * Configures preemptive authentication on this client. Ignores blank username input. *//*from ww w .ja v a 2 s.co m*/ public HttpClientConfigurator authentication(String username, String password, boolean allowAnyHost) { if (StringUtils.isNotBlank(username)) { if (StringUtils.isBlank(host)) { throw new IllegalStateException("Cannot configure authentication when host is not set."); } AuthScope authscope = allowAnyHost ? new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) : new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM); credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password)); builder.addInterceptorFirst(new PreemptiveAuthInterceptor()); } return this; }
From source file:org.eclipse.mylyn.commons.http.HttpUtil.java
public static HttpContext getHttpContext(AbstractHttpClient client, AbstractWebLocation location, HttpContext previousContext, IProgressMonitor progressMonitor) { Assert.isNotNull(client);//from w ww . j a v a 2s. c o m Assert.isNotNull(location); String url = location.getUrl(); String host = getHost(url); int port = getPort(url); configureHttpClientConnectionManager(client); HttpContext context = previousContext; if (context == null) { context = new BasicHttpContext(); } configureHttpClientProxy(client, context, location); AuthenticationCredentials authCreds = location.getCredentials(AuthenticationType.HTTP); if (authCreds != null) { AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM); Credentials credentials = getHttpClientCredentials(authCreds, host); if (credentials instanceof NTCredentials) { List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.NTLM); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); } else { List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); client.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); } client.getCredentialsProvider().setCredentials(authScope, credentials); } if (isRepositoryHttps(url)) { Scheme sch = new Scheme("https", HTTPS_PORT, sslSocketFactory); //$NON-NLS-1$ client.getConnectionManager().getSchemeRegistry().register(sch); } else { Scheme sch = new Scheme("http", HTTP_PORT, socketFactory); //$NON-NLS-1$ client.getConnectionManager().getSchemeRegistry().register(sch); } return context; }
From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java
public static DefaultHttpClient getLoginHttpClient(String userName, String password) { try {/*from w ww . ja v a 2 s . c om*/ HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); HttpConnectionParams.setConnectionTimeout(params, 300000); HttpConnectionParams.setSocketBufferSize(params, 10485760); HttpConnectionParams.setSoTimeout(params, 300000); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params); httpClient.getCredentialsProvider().setCredentials( new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), new UsernamePasswordCredentials(userName, password)); return httpClient; } catch (Exception e) { e.printStackTrace(); return new DefaultHttpClient(); } }
From source file:de.betterform.connector.http.AbstractHTTPConnector.java
protected void execute(HttpRequestBase httpRequestBase) throws Exception { // (new HttpClient()).executeMethod(httpMethod); //HttpClient client = new HttpClient(); HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams); if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("SSL_CUSTOM_SCHEME"); LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: " + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT)); String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT); if (contextPath != null) { initSSLScheme(contextPath);/*from w ww . j a v a 2 s .c om*/ } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("context params>>>"); Map map = getContext(); Iterator keys = map.keySet().iterator(); while (keys.hasNext()) { String key = keys.next().toString(); Object value = map.get(key); if (value != null) LOGGER.debug(key + "=" + value.toString()); } LOGGER.debug("<<<end params"); } String username = null; String password = null; String realm = null; //add custom header to signal XFormsFilter to not process this internal request //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true"); httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true"); /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders if (getContext().containsKey(HTTP_REQUEST_HEADERS)) { RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS); // Iterator it = Map headersToAdd = new HashMap(); for (RequestHeader header : httpRequestHeaders.getAllHeaders()) { String headername = header.getName(); String headervalue = header.getValue(); if (headername.equals("username")) { username = headervalue; } else if (headername.equals("password")) { password = headervalue; } else if (headername.equals("realm")) { realm = headervalue; } else { if (headersToAdd.containsKey(headername)) { String formerValue = (String) headersToAdd.get(headername); headersToAdd.put(headername, formerValue + "," + headervalue); } else { if (headername.equals("accept-encoding")) { // do nothing LOGGER.debug("do not add accept-encoding:" + headervalue + " for request"); } else { headersToAdd.put(headername, headervalue); if (LOGGER.isDebugEnabled()) { LOGGER.debug("setting header: " + headername + " value: " + headervalue); } } } } } Iterator keyIterator = headersToAdd.keySet().iterator(); while (keyIterator.hasNext()) { String key = (String) keyIterator.next(); //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key))); httpRequestBase.setHeader(key, (String) headersToAdd.get(key)); //httpRequestBase.addHeader(key, (String) headersToAdd.get(key)); } } if (httpRequestBase.containsHeader("Content-Length")) { //remove content-length if present httpclient will recalucalte the value. httpRequestBase.removeHeaders("Content-Length"); } if (username != null && password != null) { URI targetURI = null; //targetURI = httpMethod.getURI(); targetURI = httpRequestBase.getURI(); //client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); if (realm == null) { realm = AuthScope.ANY_REALM; } //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); client.getCredentialsProvider() .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(targetURI.getHost()), basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); //Needed? httpMethod.setDoAuthentication(true); } //alternative method for non-tomcat servers if (getContext().containsKey(REQUEST_COOKIE)) { //HttpState state = client.getState(); HttpParams state = client.getParams(); //state.setCookiePolicy(CookiePolicy.COMPATIBILITY); state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) { Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE); if (cookiesIn[0] != null) { for (int i = 0; i < cookiesIn.length; i++) { Cookie cookie = cookiesIn[i]; //state.addCookie(cookie); client.getCookieStore().addCookie(cookie); } /* Cookie[] cookies = state.getCookies(); Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies); httpMethod.setRequestHeader(cookieOut); client.setState(state); */ List<Cookie> cookies = client.getCookieStore().getCookies(); List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies); Header[] headers = cookieHeaders.toArray(new Header[0]); for (int i = 0; i < headers.length; i++) { httpRequestBase.addHeader(headers[i]); } client.setParams(state); } } else { throw new MalformedCookieException( "Cookies must be passed as org.apache.commons.httpclient.Cookie objects."); } } if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("Using customSSL-Protocol-Handler"); Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) .iterator(); while (schemes.hasNext()) { client.getConnectionManager().getSchemeRegistry().register(schemes.next()); } } if (httpRequestBase.getURI().isAbsolute()) { httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost()); } HttpResponse httpResponse = client.execute(httpRequestBase); statusCode = httpResponse.getStatusLine().getStatusCode(); reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); try { if (statusCode >= 300) { // Allow 302 only if (statusCode != 302) { throw new XFormsInternalSubmitException(statusCode, reasonPhrase, EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } } this.handleHttpMethod(httpResponse); } catch (Exception e) { LOGGER.trace("AbstractHTTPConnector Exception: ", e); try { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } catch (IOException e1) { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR); } } }
From source file:org.artifactory.util.HttpClientConfigurator.java
public HttpClientConfigurator enableTokenAuthentication(boolean enableTokenAuthentication, String username, String password) {// w ww. j a v a 2s . c om if (enableTokenAuthentication) { if (StringUtils.isBlank(host)) { throw new IllegalStateException("Cannot configure authentication when host is not set."); } config.setTargetPreferredAuthSchemes(Collections.singletonList("Bearer")); // We need dummy credentials otherwise we won't respond to a challenge properly AuthScope authScope = new AuthScope(host, AuthScope.ANY_PORT, AuthScope.ANY_REALM); // Dummy:dummy is the specification for forcing token authentication UsernamePasswordCredentials dummyCredentials = new UsernamePasswordCredentials("dummy", "dummy"); credsProvider.setCredentials(authScope, dummyCredentials); // The real credentials are passed to the Bearer that will get the token with them UsernamePasswordCredentials realCredentials = null; if (StringUtils.isNotBlank(username)) { realCredentials = new UsernamePasswordCredentials(username, password); } Registry<AuthSchemeProvider> bearerRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("Bearer", new BearerSchemeFactory(realCredentials)).build(); builder.setDefaultAuthSchemeRegistry(bearerRegistry); } return this; }