List of usage examples for org.apache.http.auth AuthScope getRealm
public String getRealm()
From source file:httpclient.client.ClientInteractiveAuthentication.java
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); // 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(); if (entity != null) { entity.consumeContent();// w ww.jav a 2 s .c om } int sc = response.getStatusLine().getStatusCode(); AuthState authState = null; if (sc == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (authState != null) { System.out.println("----------------------------------------"); AuthScope authScope = authState.getAuthScope(); System.out.println("Please provide credentials"); System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort()); System.out.println(" Realm: " + authScope.getRealm()); 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(authScope, creds); trying = true; } else { trying = false; } } else { trying = false; } } // 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:com.android.sdklib.internal.repository.UrlOpener.java
private static InputStream openWithHttpClient(String url, ITaskMonitor monitor) throws IOException, ClientProtocolException, CanceledByUserException { UserCredentials result = null;//from ww w.jav a 2 s .co m String realm = null; // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(); // create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet(url); // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. return new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { super.close(); // since Http Client is no longer needed, close it httpClient.getConnectionManager().shutdown(); } }; } } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:com.android.tools.idea.sdk.remote.internal.UrlOpener.java
@NonNull private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url, @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException { UserCredentials result = null;//from w w w. j a v a2s.co m String realm = null; HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs); HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs); // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(params); // create local execution context HttpContext localContext = new BasicHttpContext(); final HttpGet httpGet = new HttpGet(url); if (inHeaders != null) { for (Header header : inHeaders) { httpGet.addHeader(header); } } // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); if (DEBUG) { try { URI uri = new URI(url); ProxySelector sel = routePlanner.getProxySelector(); if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$ List<Proxy> list = sel.select(uri); System.out.printf("SdkLib.UrlOpener:\n Connect to: %s\n Proxy List: %s\n", //$NON-NLS-1$ url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$ } } catch (Exception e) { System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$ url, e.toString()); } } boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpGet, localContext); int statusCode = response.getStatusLine().getStatusCode(); if (DEBUG) { System.out.printf(" Status: %d\n", statusCode); //$NON-NLS-1$ } // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. InputStream is = new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { // Since Http Client is no longer needed, close it. // Bug #21167: we need to tell http client to shutdown // first, otherwise the super.close() would continue // downloading and not return till complete. httpClient.getConnectionManager().shutdown(); super.close(); } }; HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(is, outResponse); } } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) { // It's ok to not have an entity (e.g. nothing to download) for a 304 HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine()); outResponse.setHeaders(response.getAllHeaders()); outResponse.setLocale(response.getLocale()); return Pair.of(null, outResponse); } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:com.asakusafw.shafu.internal.core.net.ShafuCredentialsProvider.java
@Override public Credentials getCredentials(AuthScope authscope) { String host = authscope.getHost(); if (host != AuthScope.ANY_HOST) { Scope scope = new Scope(authscope.getScheme(), host, authscope.getPort(), authscope.getRealm()); for (IHttpCredentialsProvider provider : Activator.getExtensions().createHttpCredentialsProvider()) { try { IHttpCredentials creds = provider.find(scope); if (creds != null) { return new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword()); }/*from w ww. j a v a2s .c o m*/ } catch (CoreException e) { LogUtil.log(e.getStatus()); } } } return super.getCredentials(authscope); }
From source file:com.nesscomputing.httpclient.factory.httpclient4.InternalCredentialsProvider.java
@Override public Credentials getCredentials(final AuthScope authScope) { for (final HttpClientAuthProvider authProvider : authProviders) { if (authProvider.acceptRequest(authScope.getScheme(), authScope.getHost(), authScope.getPort(), authScope.getRealm())) { return new Credentials() { @Override// ww w . jav a 2 s . c o m public Principal getUserPrincipal() { return new BasicUserPrincipal(authProvider.getUser()); } @Override public String getPassword() { return authProvider.getPassword(); } }; } } return null; }
From source file:org.apache.maven.wagon.providers.http.BasicAuthScopeTest.java
/** * Test AuthScope override for realm value overridden *//* w w w . j a v a 2s. c om*/ @Test public void testGetScopeRealmOverridden() { BasicAuthScope scope = new BasicAuthScope(); scope.setRealm("override-realm"); AuthScope authScope = scope.getScope("original.host.com", 3456); Assert.assertEquals("original.host.com", authScope.getHost()); Assert.assertEquals(3456, authScope.getPort()); Assert.assertEquals("override-realm", authScope.getRealm()); }
From source file:org.apache.maven.wagon.providers.http.BasicAuthScopeTest.java
/** * Test AuthScope override for all values overridden *//*from www . j av a 2 s . co m*/ @Test public void testGetScopeAllOverridden() { BasicAuthScope scope = new BasicAuthScope(); scope.setHost("override.host.com"); scope.setPort("1234"); scope.setRealm("override-realm"); AuthScope authScope = scope.getScope("original.host.com", 3456); Assert.assertEquals("override.host.com", authScope.getHost()); Assert.assertEquals(1234, authScope.getPort()); Assert.assertEquals("override-realm", authScope.getRealm()); }
From source file:org.apache.maven.wagon.providers.http.BasicAuthScopeTest.java
/** * Test AuthScope override with no overriding values set. Nothing should * change in original host/port.// ww w . j a v a2s. c o m */ @Test public void testGetScopeNothingOverridden() { BasicAuthScope scope = new BasicAuthScope(); AuthScope authScope = scope.getScope("original.host.com", 3456); Assert.assertEquals("original.host.com", authScope.getHost()); Assert.assertEquals(3456, authScope.getPort()); Assert.assertEquals(AuthScope.ANY_REALM, authScope.getRealm()); }
From source file:org.apache.maven.wagon.providers.http.BasicAuthScopeTest.java
/** * Test AuthScope override for all values overridden with "ANY" *//*from ww w . j a v a 2 s .c om*/ @Test public void testGetScopeAllAny() { BasicAuthScope scope = new BasicAuthScope(); scope.setHost("ANY"); scope.setPort("ANY"); scope.setRealm("ANY"); AuthScope authScope = scope.getScope("original.host.com", 3456); Assert.assertEquals(AuthScope.ANY_HOST, authScope.getHost()); Assert.assertEquals(AuthScope.ANY_PORT, authScope.getPort()); Assert.assertEquals(AuthScope.ANY_REALM, authScope.getRealm()); }
From source file:org.apache.taverna.activities.rest.RESTActivityCredentialsProvider.java
@Override public Credentials getCredentials(AuthScope authscope) { logger.info("Looking for credentials for: Host - " + authscope.getHost() + ";" + "Port - " + authscope.getPort() + ";" + "Realm - " + authscope.getRealm() + ";" + "Authentication scheme - " + authscope.getScheme());//from w w w . j a v a 2 s. c om // Ask the superclass first Credentials creds = super.getCredentials(authscope); if (creds != null) { /* * We have used setCredentials() on this class (for proxy host, * port, username,password) just before we invoked the http request, * which will then pick the proxy credentials up from here. */ return creds; } // Otherwise, ask Credential Manager if is can provide the credential String AUTHENTICATION_REQUEST_MSG = "This REST service requires authentication in " + authscope.getRealm(); try { UsernamePassword credentials = null; /* * if port is 80 - use HTTP, don't append port if port is 443 - use * HTTPS, don't append port any other port - append port + do 2 * tests: * * --- test HTTPS first has...() * --- if not there, do get...() for HTTP (which will save the thing) * * (save both these entries for HTTP + HTTPS if not there) */ // build the service URI back to front StringBuilder serviceURI = new StringBuilder(); serviceURI.insert(0, "/#" + URLEncoder.encode(authscope.getRealm(), "UTF-16")); if (authscope.getPort() != DEFAULT_HTTP_PORT && authscope.getPort() != DEFAULT_HTTPS_PORT) { // non-default port - add port name to the URI serviceURI.insert(0, ":" + authscope.getPort()); } serviceURI.insert(0, authscope.getHost()); serviceURI.insert(0, "://"); // now the URI is complete, apart from the protocol name if (authscope.getPort() == DEFAULT_HTTP_PORT || authscope.getPort() == DEFAULT_HTTPS_PORT) { // definitely HTTP or HTTPS serviceURI.insert(0, (authscope.getPort() == DEFAULT_HTTP_PORT ? HTTP_PROTOCOL : HTTPS_PROTOCOL)); // request credentials from CrendentialManager credentials = credentialManager.getUsernameAndPasswordForService(URI.create(serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); } else { /* * non-default port - will need to try both HTTP and HTTPS; just * check (no pop-up will be shown) if credentials are there - * one protocol that matched will be used; if */ if (credentialManager .hasUsernamePasswordForService(URI.create(HTTPS_PROTOCOL + serviceURI.toString()))) { credentials = credentialManager.getUsernameAndPasswordForService( URI.create(HTTPS_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); } else if (credentialManager .hasUsernamePasswordForService(URI.create(HTTP_PROTOCOL + serviceURI.toString()))) { credentials = credentialManager.getUsernameAndPasswordForService( URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); } else { /* * Neither of the two options succeeded, request details with a * popup for HTTP... */ credentials = credentialManager.getUsernameAndPasswordForService( URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); /* * ...then save a second entry with HTTPS protocol (if the * user has chosen to save the credentials) */ if (credentials != null && credentials.isShouldSave()) { credentialManager.addUsernameAndPasswordForService(credentials, URI.create(HTTPS_PROTOCOL + serviceURI.toString())); } } } if (credentials != null) { logger.info("Credentials obtained successfully"); return new RESTActivityCredentials(credentials.getUsername(), credentials.getPasswordAsString()); } } catch (Exception e) { logger.error("Unexpected error while trying to obtain user's credential from CredentialManager", e); } // error or nothing was found logger.info("Credentials not found - the user must have refused to enter them."); return null; }