List of usage examples for org.apache.http.auth AuthScheme getRealm
String getRealm();
From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from ww w . j av a 2s.c o m*/ // Create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet("http://localhost/test"); boolean trying = true; while (trying) { System.out.println("executing request " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget, localContext); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); // Consume response content HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); int sc = response.getStatusLine().getStatusCode(); AuthState authState = null; HttpHost authhost = null; if (sc == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); } if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST); } if (authState != null) { System.out.println("----------------------------------------"); AuthScheme authscheme = authState.getAuthScheme(); System.out.println("Please provide credentials for " + authscheme.getRealm() + "@" + authhost.toHostString()); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter username: "); String user = console.readLine(); System.out.print("Enter password: "); String password = console.readLine(); if (user != null && user.length() > 0) { Credentials creds = new UsernamePasswordCredentials(user, password); httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds); trying = true; } else { trying = false; } } else { trying = false; } } } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } }
From source file:glaze.oauth.PreemptiveAuthorizer.java
/** * If no auth scheme has been selected for the given context, consider each * of the preferred auth schemes and select the first one for which an * AuthScheme and matching Credentials are available. *///from w w w .j a v a 2s.co m @SuppressWarnings("unchecked") public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState != null && authState.getAuthScheme() != null) { return; } HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); CredentialsProvider provider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY); HttpParams params = request.getParams(); for (String schemeName : (Iterable<String>) params.getParameter(AuthPNames.PROXY_AUTH_PREF)) { AuthScheme scheme = schemes.getAuthScheme(schemeName, params); if (scheme != null) { AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(), scheme.getSchemeName()); Credentials creds = provider.getCredentials(targetScope); if (creds != null) { authState.update(scheme, creds); return; } } } }
From source file:net.oauth.client.httpclient4.PreemptiveAuthorizer.java
/** * If no auth scheme has been selected for the given context, consider each * of the preferred auth schemes and select the first one for which an * AuthScheme and matching Credentials are available. */// w w w . j av a 2s.c om public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); if (authState != null && authState.getAuthScheme() != null) { return; } HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); CredentialsProvider creds = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); AuthSchemeRegistry schemes = (AuthSchemeRegistry) context.getAttribute(ClientContext.AUTHSCHEME_REGISTRY); for (Object schemeName : (Iterable) context.getAttribute(ClientContext.AUTH_SCHEME_PREF)) { AuthScheme scheme = schemes.getAuthScheme(schemeName.toString(), request.getParams()); if (scheme != null) { AuthScope targetScope = new AuthScope(target.getHostName(), target.getPort(), scheme.getRealm(), scheme.getSchemeName()); Credentials cred = creds.getCredentials(targetScope); if (cred != null) { authState.setAuthScheme(scheme); authState.setCredentials(cred); return; } } } }
From source file:com.grendelscan.commons.http.apache_overrides.client.CustomClientRequestDirector.java
private void updateAuthState(final AuthState authState, final HttpHost host, final CredentialsProvider credsProvider) { if (!authState.isValid()) { return;//from www . j a va 2 s .co m } String hostname = host.getHostName(); int port = host.getPort(); if (port < 0) { Scheme scheme = connManager.getSchemeRegistry().getScheme(host); port = scheme.getDefaultPort(); } AuthScheme authScheme = authState.getAuthScheme(); AuthScope authScope = new AuthScope(hostname, port, authScheme.getRealm(), authScheme.getSchemeName()); LOGGER.trace("Authentication scope: " + authScope); Credentials creds = authState.getCredentials(); if (creds == null) { creds = credsProvider.getCredentials(authScope); if (creds != null) { LOGGER.trace("Found credentials"); } else { LOGGER.trace("Credentials not found"); } } else { if (authScheme.isComplete()) { LOGGER.debug("Authentication failed"); creds = null; } } authState.setAuthScope(authScope); authState.setCredentials(creds); }
From source file:org.robolectric.shadows.httpclient.DefaultRequestDirector.java
private void updateAuthState(final AuthState authState, final HttpHost host, final CredentialsProvider credsProvider) { if (!authState.isValid()) { return;//from w ww .j av a 2 s.c o m } String hostname = host.getHostName(); int port = host.getPort(); if (port < 0) { Scheme scheme = connManager.getSchemeRegistry().getScheme(host); port = scheme.getDefaultPort(); } AuthScheme authScheme = authState.getAuthScheme(); AuthScope authScope = new AuthScope(hostname, port, authScheme.getRealm(), authScheme.getSchemeName()); if (this.log.isDebugEnabled()) { this.log.debug("Authentication scope: " + authScope); } Credentials creds = authState.getCredentials(); if (creds == null) { creds = credsProvider.getCredentials(authScope); if (this.log.isDebugEnabled()) { if (creds != null) { this.log.debug("Found credentials"); } else { this.log.debug("Credentials not found"); } } } else { if (authScheme.isComplete()) { this.log.debug("Authentication failed"); creds = null; } } authState.setAuthScope(authScope); authState.setCredentials(creds); }
From source file:org.archive.modules.fetcher.FetchHTTP.java
/** * Server is looking for basic/digest auth credentials (RFC2617). If we have * any, put them into the CrawlURI and have it come around again. * Presence of the credential serves as flag to frontier to requeue * promptly. If we already tried this domain and still got a 401, then our * credentials are bad. Remove them and let this curi die. * @param httpClient // ww w . j ava2 s .co m * @param response 401 http response * @param curi * CrawlURI that got a 401. */ protected void handle401(HttpResponse response, final CrawlURI curi) { Map<String, String> challenges = extractChallenges(response, curi, TargetAuthenticationStrategy.INSTANCE); AuthScheme authscheme = chooseAuthScheme(challenges, HttpHeaders.WWW_AUTHENTICATE); // remember WWW-Authenticate headers for later use curi.setHttpAuthChallenges(challenges); if (authscheme == null) { return; } String realm = authscheme.getRealm(); // Look to see if this curi had rfc2617 avatars loaded. If so, are // any of them for this realm? If so, then the credential failed // if we got a 401 and it should be let die a natural 401 death. Set<Credential> curiRfc2617Credentials = getCredentials(curi, HttpAuthenticationCredential.class); HttpAuthenticationCredential extant = HttpAuthenticationCredential.getByRealm(curiRfc2617Credentials, realm, curi); if (extant != null) { // Then, already tried this credential. Remove ANY rfc2617 // credential since presence of a rfc2617 credential serves // as flag to frontier to requeue this curi and let the curi // die a natural death. extant.detachAll(curi); logger.warning("Auth failed (401) though supplied realm " + realm + " to " + curi.toString()); } else { // Look see if we have a credential that corresponds to this // realm in credential store. Filter by type and credential // domain. If not, let this curi die. Else, add it to the // curi and let it come around again. Add in the AuthScheme // we got too. Its needed when we go to run the Auth on // second time around. String serverKey = getServerKey(curi); CrawlServer server = serverCache.getServerFor(serverKey); Set<Credential> storeRfc2617Credentials = getCredentialStore().subset(curi, HttpAuthenticationCredential.class, server.getName()); if (storeRfc2617Credentials == null || storeRfc2617Credentials.size() <= 0) { logger.fine("No rfc2617 credentials for " + curi); } else { HttpAuthenticationCredential found = HttpAuthenticationCredential .getByRealm(storeRfc2617Credentials, realm, curi); if (found == null) { logger.fine("No rfc2617 credentials for realm " + realm + " in " + curi); } else { found.attach(curi); logger.fine("Found credential for scheme " + authscheme + " realm " + realm + " in store for " + curi.toString()); } } } }
From source file:org.archive.modules.fetcher.FetchHTTP.java
protected AuthScheme chooseAuthScheme(Map<String, String> challenges, String challengeHeaderKey) { HashSet<String> authSchemesLeftToTry = new HashSet<String>(challenges.keySet()); for (String authSchemeName : new String[] { "digest", "basic" }) { if (authSchemesLeftToTry.remove(authSchemeName)) { AuthScheme authScheme = AUTH_SCHEME_REGISTRY.lookup(authSchemeName).create(null); ;/*from www . j ava 2 s.c o m*/ BasicHeader challenge = new BasicHeader(challengeHeaderKey, challenges.get(authSchemeName)); try { authScheme.processChallenge(challenge); } catch (MalformedChallengeException e) { logger.fine(e.getMessage() + " " + challenge); continue; } if (authScheme.isConnectionBased()) { logger.fine("Connection based " + authScheme); continue; } if (authScheme.getRealm() == null || authScheme.getRealm().length() <= 0) { logger.fine("Empty realm " + authScheme); continue; } return authScheme; } } for (String unsupportedSchemeName : authSchemesLeftToTry) { logger.fine("Unsupported http auth scheme: " + unsupportedSchemeName); } return null; }
From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java
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 Queue<AuthOption> options = new LinkedList<AuthOption>(); final CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); if (credsProvider == null) { this.log.debug("Credentials provider not set in the context"); return options; }/* w w w . j av a2s . c om*/ final AuthScheme authScheme; try { authScheme = this.handler.selectScheme(challenges, response, context); } catch (final AuthenticationException ex) { if (this.log.isWarnEnabled()) { this.log.warn(ex.getMessage(), ex); } return options; } final String id = authScheme.getSchemeName(); final Header challenge = challenges.get(id.toLowerCase(Locale.US)); 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)); } return options; }
From source file:org.apache.http.impl.client.AuthenticationStrategyImpl.java
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; }/*from w ww.j a v a 2 s . c o m*/ 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.US)); 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; }