org.apache.commons.httpclient.Credentials Java Examples
The following examples show how to use
org.apache.commons.httpclient.Credentials.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpTemplateDownloader.java From cloudstack with Apache License 2.0 | 7 votes |
private void checkCredentials(String user, String password) { try { Pair<String, Integer> hostAndPort = UriUtils.validateUrl(downloadUrl); if ((user != null) && (password != null)) { client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(user, password); client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds); s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); } else { s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second()); } } catch (IllegalArgumentException iae) { errorString = iae.getMessage(); status = TemplateDownloader.Status.UNRECOVERABLE_ERROR; inited = false; } }
Example #2
Source File: SignerCredentialsProvider.java From httpsig-java with The Unlicense | 6 votes |
public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy) throws CredentialsNotAvailableException { if (Constants.SCHEME.equals(scheme.getSchemeName())) { if (signer == null) { throw new CredentialsNotAvailableException("SSHKey Signer not available"); } else { return new SignerCredentials(signer); } } else { if (this.delegatee != null) { return this.delegatee.getCredentials(scheme, host, port, proxy); } } return null; }
Example #3
Source File: EsApiKeyAuthScheme.java From elasticsearch-hadoop with Apache License 2.0 | 6 votes |
/** * Implementation method for authentication */ private String authenticate(Credentials credentials) throws AuthenticationException { if (!(credentials instanceof EsApiKeyCredentials)) { throw new AuthenticationException("Incorrect credentials type provided. Expected [" + EsApiKeyCredentials.class.getName() + "] but got [" + credentials.getClass().getName() + "]"); } EsApiKeyCredentials esApiKeyCredentials = ((EsApiKeyCredentials) credentials); String authString = null; if (esApiKeyCredentials.getToken() != null && StringUtils.hasText(esApiKeyCredentials.getToken().getName())) { EsToken token = esApiKeyCredentials.getToken(); String keyComponents = token.getId() + ":" + token.getApiKey(); byte[] base64Encoded = Base64.encodeBase64(keyComponents.getBytes(StringUtils.UTF_8)); String tokenText = new String(base64Encoded, StringUtils.UTF_8); authString = EsHadoopAuthPolicies.APIKEY + " " + tokenText; } return authString; }
Example #4
Source File: UriUtils.java From cloudstack with Apache License 2.0 | 6 votes |
public static InputStream getInputStreamFromUrl(String url, String user, String password) { try { Pair<String, Integer> hostAndPort = validateUrl(url); HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager()); if ((user != null) && (password != null)) { httpclient.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(user, password); httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds); s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); } // Execute the method. GetMethod method = new GetMethod(url); int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { s_logger.error("Failed to read from URL: " + url); return null; } return method.getResponseBodyAsStream(); } catch (Exception ex) { s_logger.error("Failed to read from URL: " + url); return null; } }
Example #5
Source File: HttpClientFactory.java From olat with Apache License 2.0 | 6 votes |
/** * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs * * @param user * can be NULL * @param password * can be NULL * @return HttpClient */ public static HttpClient getHttpClientInstance(String user, String password) { HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionParams params = connectionManager.getParams(); // wait max 10 seconds to establish connection params.setConnectionTimeout(10000); // a read() call on the InputStream associated with this Socket // will block for only this amount params.setSoTimeout(10000); HttpClient c = new HttpClient(connectionManager); // use basic authentication if available if (user != null && user.length() > 0) { AuthScope authScope = new AuthScope(null, -1, null); Credentials credentials = new UsernamePasswordCredentials(user, password); c.getState().setCredentials(authScope, credentials); } return c; }
Example #6
Source File: HttpClientFactory.java From olat with Apache License 2.0 | 6 votes |
/** * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs * * @param user * can be NULL * @param password * can be NULL * @return HttpClient */ public static HttpClient getHttpClientInstance(String user, String password) { HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionParams params = connectionManager.getParams(); // wait max 10 seconds to establish connection params.setConnectionTimeout(10000); // a read() call on the InputStream associated with this Socket // will block for only this amount params.setSoTimeout(10000); HttpClient c = new HttpClient(connectionManager); // use basic authentication if available if (user != null && user.length() > 0) { AuthScope authScope = new AuthScope(null, -1, null); Credentials credentials = new UsernamePasswordCredentials(user, password); c.getState().setCredentials(authScope, credentials); } return c; }
Example #7
Source File: HttpUtil.java From openhab1-addons with Eclipse Public License 2.0 | 6 votes |
/** * Extracts username and password from the given <code>url</code>. A valid * url to extract {@link Credentials} from looks like: * * <pre> * http://username:[email protected] * </pre> * * @param url the URL to extract {@link Credentials} from * * @return the exracted Credentials or <code>null</code> if the given * <code>url</code> does not contain credentials */ protected static Credentials extractCredentials(String url) { Matcher matcher = URL_CREDENTIALS_PATTERN.matcher(url); if (matcher.matches()) { matcher.reset(); String username = ""; String password = ""; while (matcher.find()) { username = matcher.group(1); password = matcher.group(2); } Credentials credentials = new UsernamePasswordCredentials(username, password); return credentials; } return null; }
Example #8
Source File: BasicAuthLoader.java From development with Apache License 2.0 | 6 votes |
/** * Retrieves the content under the given URL with username and passwort * authentication. * * @param url * the URL to read * @param username * @param password * @return the read content. * @throws IOException * if an I/O exception occurs. */ private static byte[] getUrlContent(URL url, String username, String password) throws IOException { final HttpClient client = new HttpClient(); // Set credentials: client.getParams().setAuthenticationPreemptive(true); final Credentials credentials = new UsernamePasswordCredentials( username, password); client.getState() .setCredentials( new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), credentials); // Retrieve content: final GetMethod method = new GetMethod(url.toString()); final int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { throw new IOException("Error " + status + " while retrieving " + url); } return method.getResponseBody(); }
Example #9
Source File: RORClientTest.java From development with Apache License 2.0 | 6 votes |
@Test public void createClient() throws Exception { // given System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE); System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE); System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_USER_VALUE); System.setProperty(HTTPS_PROXY_PASSWORD, HTTPS_PROXY_PASSWORD_VALUE); Credentials proxyCredentials = new UsernamePasswordCredentials( HTTPS_PROXY_USER_VALUE, HTTPS_PROXY_PASSWORD_VALUE); AuthScope authScope = new AuthScope(HTTPS_PROXY_HOST_VALUE, Integer.parseInt(HTTPS_PROXY_PORT_VALUE)); // when HttpClient client = vdcClient.createHttpClient(); // then assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration() .getProxyHost()); assertEquals(HTTPS_PROXY_PORT_VALUE, String.valueOf(client.getHostConfiguration().getProxyPort())); assertEquals(proxyCredentials, client.getState().getProxyCredentials(authScope)); }
Example #10
Source File: PortFactory.java From development with Apache License 2.0 | 6 votes |
/** * Retrieves the content under the given URL with username and passwort * authentication. * * @param url * @param username * @param password * @return * @throws IOException */ private static byte[] getUrlContent(URL url, String username, String password) throws IOException { final HttpClient client = new HttpClient(); // Set credentials: client.getParams().setAuthenticationPreemptive(true); final Credentials credentials = new UsernamePasswordCredentials( username, password); client.getState() .setCredentials( new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), credentials); // Retrieve content: final GetMethod method = new GetMethod(url.toString()); final int status = client.executeMethod(method); if (status != HttpStatus.SC_OK) { throw new IOException("Error " + status + " while retrieving " + url); } return method.getResponseBody(); }
Example #11
Source File: UriUtils.java From cosmic with Apache License 2.0 | 6 votes |
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) { try { final Pair<String, Integer> hostAndPort = validateUrl(url); final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager()); if ((user != null) && (password != null)) { httpclient.getParams().setAuthenticationPreemptive(true); final Credentials defaultcreds = new UsernamePasswordCredentials(user, password); httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds); s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second()); } // Execute the method. final GetMethod method = new GetMethod(url); final int statusCode = httpclient.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { s_logger.error("Failed to read from URL: " + url); return null; } return method.getResponseBodyAsStream(); } catch (final Exception ex) { s_logger.error("Failed to read from URL: " + url); return null; } }
Example #12
Source File: HttpAuthenticator.java From knopflerfish.org with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static boolean doAuthenticateDefault( HttpMethod method, HttpConnection conn, HttpState state, boolean proxy) throws AuthenticationException { if (method == null) { throw new IllegalArgumentException("HTTP method may not be null"); } if (state == null) { throw new IllegalArgumentException("HTTP state may not be null"); } String host = null; if (conn != null) { host = proxy ? conn.getProxyHost() : conn.getHost(); } Credentials credentials = proxy ? state.getProxyCredentials(null, host) : state.getCredentials(null, host); if (credentials == null) { return false; } if (!(credentials instanceof UsernamePasswordCredentials)) { throw new InvalidCredentialsException( "Credentials cannot be used for basic authentication: " + credentials.toString()); } String auth = BasicScheme.authenticate( (UsernamePasswordCredentials) credentials, method.getParams().getCredentialCharset()); if (auth != null) { String s = proxy ? PROXY_AUTH_RESP : WWW_AUTH_RESP; Header header = new Header(s, auth, true); method.addRequestHeader(header); return true; } else { return false; } }
Example #13
Source File: PhoneValidationUtils.java From fenixedu-academic with GNU Lesser General Public License v3.0 | 5 votes |
private void initCIISTSMSGateway() { final String CIIST_SMS_USERNAME = FenixEduAcademicConfiguration.getConfiguration().getCIISTSMSUsername(); final String CIIST_SMS_PASSWORD = FenixEduAcademicConfiguration.getConfiguration().getCIISTSMSPassword(); CIIST_SMS_GATEWAY_URL = FenixEduAcademicConfiguration.getConfiguration().getCIISTSMSGatewayUrl(); if (!StringUtils.isEmpty(CIIST_SMS_USERNAME) && !StringUtils.isEmpty(CIIST_SMS_PASSWORD)) { CIIST_CLIENT = new HttpClient(); Credentials credentials = new UsernamePasswordCredentials(CIIST_SMS_USERNAME, CIIST_SMS_PASSWORD); CIIST_CLIENT.getState().setCredentials(AuthScope.ANY, credentials); } }
Example #14
Source File: HttpClientFeedFetcherTest.java From rome with Apache License 2.0 | 5 votes |
/** * @see com.rometools.rome.fetcher.impl.AbstractJettyTest#getAuthenticatedFeedFetcher() */ @Override public FeedFetcher getAuthenticatedFeedFetcher() { return new HttpClientFeedFetcher(null, new HttpClientFeedFetcher.CredentialSupplier() { @Override public Credentials getCredentials(final String realm, final String host) { if ("localhost".equals(host)) { return new UsernamePasswordCredentials("username", "password"); } else { return null; } } }); }
Example #15
Source File: InstancesManagerServiceImpl.java From geofence with GNU General Public License v2.0 | 5 votes |
private void setAuth(HttpClient client, String url, String username, String pw) throws MalformedURLException { URL u = new URL(url); if(username != null && pw != null) { Credentials defaultcreds = new UsernamePasswordCredentials(username, pw); client.getState().setCredentials(new AuthScope(u.getHost(), u.getPort()), defaultcreds); client.getParams().setAuthenticationPreemptive(true); // GS2 by default always requires authentication } else { if(logger.isDebugEnabled()) { logger.debug("Not setting credentials to access to " + url); } } }
Example #16
Source File: RestClient.java From Kylin with Apache License 2.0 | 5 votes |
private void init(String host, int port, String userName, String password) { this.host = host; this.port = port; this.userName = userName; this.password = password; this.baseUrl = "http://" + host + ":" + port + "/kylin/api"; client = new HttpClient(); if (userName != null && password != null) { client.getParams().setAuthenticationPreemptive(true); Credentials creds = new UsernamePasswordCredentials(userName, password); client.getState().setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), creds); } }
Example #17
Source File: AbstractRemoteAlfrescoTicketImpl.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
/** * Returns the Ticket in the form used for HTTP Basic Authentication. * This should be added as the value to a HTTP Request Header with * key Authorization */ public String getAsHTTPAuthorization() { // Build from the Username and Password Pair<String,String> userPass = getAsUsernameAndPassword(); Credentials credentials = new UsernamePasswordCredentials(userPass.getFirst(), userPass.getSecond()); // Encode it into the required format String credentialsEncoded = Base64.encodeBytes( credentials.toString().getBytes(utf8), Base64.DONT_BREAK_LINES ); // Mark it as Basic, and we're done return "Basic " + credentialsEncoded; }
Example #18
Source File: HttpTemplateDownloader.java From cloudstack with Apache License 2.0 | 5 votes |
private void checkProxy(Proxy proxy) { if (proxy != null) { client.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort()); if (proxy.getUserName() != null) { Credentials proxyCreds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword()); client.getState().setProxyCredentials(AuthScope.ANY, proxyCreds); } } }
Example #19
Source File: SpnegoAuthScheme.java From elasticsearch-hadoop with Apache License 2.0 | 5 votes |
/** * Returns the text to send via the Authenticate header on the next request. */ @Override public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { try { return authenticate(credentials, URI.create(method.getURI().getURI())); } catch (URIException e) { throw new AuthenticationException("Could not determine request URI", e); } }
Example #20
Source File: Confluence.java From maven-confluence-plugin with Apache License 2.0 | 5 votes |
protected Confluence(String endpoint, ConfluenceProxy proxyInfo ) throws URISyntaxException, MalformedURLException { this(new XmlRpcClient()); if (endpoint.endsWith("/")) { endpoint = endpoint.substring(0, endpoint.length() - 1); } endpoint = ConfluenceService.Protocol.XMLRPC.addTo(endpoint); final java.net.URI serviceURI = new java.net.URI(endpoint); XmlRpcClientConfigImpl clientConfig = new XmlRpcClientConfigImpl(); clientConfig.setServerURL(serviceURI.toURL() ); clientConfig.setEnabledForExtensions(true); // add this to support attachment upload client.setConfig( clientConfig ); if( isProxyEnabled(proxyInfo, serviceURI) ) { final XmlRpcCommonsTransportFactory transportFactory = new XmlRpcCommonsTransportFactory( client ); final HttpClient httpClient = new HttpClient(); final HostConfiguration hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setProxy( proxyInfo.host, proxyInfo.port ); hostConfiguration.setHost(serviceURI.getHost(), serviceURI.getPort(), serviceURI.toURL().getProtocol()); if( !isNullOrEmpty(proxyInfo.userName) && !isNullOrEmpty(proxyInfo.password) ) { Credentials cred = new UsernamePasswordCredentials(proxyInfo.userName,proxyInfo.password); httpClient.getState().setProxyCredentials(AuthScope.ANY, cred); } transportFactory.setHttpClient( httpClient ); client.setTransportFactory( transportFactory ); } }
Example #21
Source File: CSP.java From scim2-compliance-test-suite with Apache License 2.0 | 5 votes |
@SuppressWarnings("deprecation") public String getAccessToken() { if (this.oAuth2AccessToken != null) { return this.oAuth2AccessToken; } try { HttpClient client = new HttpClient(); client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(this.getUsername(), this.getPassword()); client.getState().setCredentials(AuthScope.ANY, defaultcreds); PostMethod method = new PostMethod(this.getOAuthAuthorizationServer()); method.setRequestBody("grant_type=client_credentials"); int responseCode = client.executeMethod(method); if (responseCode != 200) { throw new RuntimeException("Failed to fetch access token form authorization server, " + this.getOAuthAuthorizationServer() + ", got response code " + responseCode); } String responseBody = method.getResponseBodyAsString(); JSONObject accessResponse = new JSONObject(responseBody); accessResponse.getString("access_token"); return (this.oAuth2AccessToken = accessResponse.getString("access_token")); } catch (Exception e) { throw new RuntimeException("Failed to read response from authorizationServer at " + this.getOAuthAuthorizationServer(), e); } }
Example #22
Source File: RORClient.java From development with Apache License 2.0 | 5 votes |
public HttpClient createHttpClient() { HttpClient client = new HttpClient(); String proxyHost = System.getProperty(HTTPS_PROXY_HOST); String proxyPort = System.getProperty(HTTPS_PROXY_PORT); String proxyUser = System.getProperty(HTTPS_PROXY_USER); String proxyPassword = System.getProperty(HTTPS_PROXY_PASSWORD); int proxyPortInt = 0; try { proxyPortInt = Integer.parseInt(proxyPort); } catch (NumberFormatException e) { // ignore } if (!useProxyByPass(this.apiUrl)) { if (proxyHost != null && proxyPortInt > 0) { client.getHostConfiguration().setProxy(proxyHost, proxyPortInt); if (proxyUser != null && proxyUser.length() > 0 && proxyPassword != null && proxyPassword.length() > 0) { HttpState state = new HttpState(); Credentials proxyCredentials = new UsernamePasswordCredentials( proxyUser, proxyPassword); state.setProxyCredentials(new AuthScope(proxyHost, proxyPortInt), proxyCredentials); client.setState(state); } } } return client; }
Example #23
Source File: AbstractSpnegoAuthSchemeTest.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
@Test public void testAuthWithReverseLookupServicePrincipal() throws Exception { // Configure logins Configuration configuration = new Configuration(); SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, configuration); UserGroupInformation.setConfiguration(configuration); // Login as Client and Execute Test UserGroupInformation client = UserGroupInformation.loginUserFromKeytabAndReturnUGI(KerberosSuite.PRINCIPAL_CLIENT, KEYTAB_FILE.getAbsolutePath()); client.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { HttpParams params = new HttpClientParams(); // Order auth schemes EsHadoopAuthPolicies.registerAuthSchemes(); List<String> authPreferences = new ArrayList<String>(); authPreferences.add(EsHadoopAuthPolicies.NEGOTIATE); params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPreferences); AuthChallengeProcessor authChallengeProcessor = new AuthChallengeProcessor(params); Map<String, String> dnsMappings = new HashMap<String, String>(); dnsMappings.put("es.build.elastic.co", "127.0.0.1"); TestMethod method = new TestMethod(); method.setHeaders(new Header[]{new Header("WWW-Authenticate", "Negotiate")}); method.setURI(new org.apache.commons.httpclient.URI("http", null, "127.0.0.1", 9200)); Credentials credentials = new SpnegoCredentials(HadoopUserProvider.create(new TestSettings()), "HTTP/[email protected]"); // Parse Challenge Map challenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders("WWW-Authenticate")); assertThat(challenges.isEmpty(), not(true)); assertThat(challenges.containsKey("negotiate"), is(true)); assertThat(challenges.get("negotiate"), is("Negotiate")); AuthScheme scheme = authChallengeProcessor.processChallenge(method.getHostAuthState(), challenges); assertNotNull(scheme); assertThat(scheme, instanceOf(SpnegoAuthScheme.class)); method.getHostAuthState().setAuthAttempted(true); // Execute Auth Header[] authHeaders = method.getRequestHeaders("Authorization"); for (Header authHeader : authHeaders) { if (authHeader.isAutogenerated()) { method.removeRequestHeader(authHeader); } } AuthState authState = method.getHostAuthState(); AuthScheme authScheme = authState.getAuthScheme(); assertNotNull(authScheme); assertThat(authScheme.isConnectionBased(), is(not(true))); // Replace scheme with test harness scheme authScheme = new TestScheme(dnsMappings); String authString = authScheme.authenticate(credentials, method); assertNotNull(authString); assertThat(authString, startsWith("Negotiate ")); method.addRequestHeader(new Header("Authorization", authString, true)); return null; } }); }
Example #24
Source File: EsApiKeyAuthScheme.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
/** * Deprecated method, can still be authenticated with credentials. */ @Override public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { return authenticate(credentials); }
Example #25
Source File: EsApiKeyAuthScheme.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
/** * Returns the text to send via the Authenticate header on the next request. */ @Override public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException { return authenticate(credentials); }
Example #26
Source File: SpnegoAuthScheme.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
/** * Deprecated method, can still be authenticated with credentials. */ @Override public String authenticate(Credentials credentials, String method, String uri) throws AuthenticationException { return authenticate(credentials, URI.create(uri)); }
Example #27
Source File: AbstractSpnegoAuthSchemeTest.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
@Test public void testAuth() throws Exception { // Configure logins Configuration configuration = new Configuration(); SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, configuration); UserGroupInformation.setConfiguration(configuration); // Login as Client and Execute Test UserGroupInformation client = UserGroupInformation.loginUserFromKeytabAndReturnUGI(KerberosSuite.PRINCIPAL_CLIENT, KEYTAB_FILE.getAbsolutePath()); client.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { HttpParams params = new HttpClientParams(); // Order auth schemes EsHadoopAuthPolicies.registerAuthSchemes(); List<String> authPreferences = new ArrayList<String>(); authPreferences.add(EsHadoopAuthPolicies.NEGOTIATE); params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPreferences); AuthChallengeProcessor authChallengeProcessor = new AuthChallengeProcessor(params); TestMethod method = new TestMethod(); method.setHeaders(new Header[]{new Header("WWW-Authenticate", "Negotiate")}); Credentials credentials = new SpnegoCredentials(HadoopUserProvider.create(new TestSettings()), KerberosSuite.PRINCIPAL_SERVER); // Parse Challenge Map challenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders("WWW-Authenticate")); assertThat(challenges.isEmpty(), not(true)); assertThat(challenges.containsKey("negotiate"), is(true)); assertThat(challenges.get("negotiate"), is("Negotiate")); AuthScheme scheme = authChallengeProcessor.processChallenge(method.getHostAuthState(), challenges); assertNotNull(scheme); assertThat(scheme, instanceOf(SpnegoAuthScheme.class)); method.getHostAuthState().setAuthAttempted(true); // Execute Auth Header[] authHeaders = method.getRequestHeaders("Authorization"); for (Header authHeader : authHeaders) { if (authHeader.isAutogenerated()) { method.removeRequestHeader(authHeader); } } AuthState authState = method.getHostAuthState(); AuthScheme authScheme = authState.getAuthScheme(); assertNotNull(authScheme); assertThat(authScheme.isConnectionBased(), is(not(true))); String authString = authScheme.authenticate(credentials, method); assertNotNull(authString); assertThat(authString, startsWith("Negotiate ")); method.addRequestHeader(new Header("Authorization", authString, true)); return null; } }); }
Example #28
Source File: AbstractSpnegoAuthSchemeTest.java From elasticsearch-hadoop with Apache License 2.0 | 4 votes |
@Test public void testAuthWithHostBasedServicePrincipal() throws Exception { // Configure logins Configuration configuration = new Configuration(); SecurityUtil.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS, configuration); UserGroupInformation.setConfiguration(configuration); // Login as Client and Execute Test UserGroupInformation client = UserGroupInformation.loginUserFromKeytabAndReturnUGI(KerberosSuite.PRINCIPAL_CLIENT, KEYTAB_FILE.getAbsolutePath()); client.doAs(new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { HttpParams params = new HttpClientParams(); // Order auth schemes EsHadoopAuthPolicies.registerAuthSchemes(); List<String> authPreferences = new ArrayList<String>(); authPreferences.add(EsHadoopAuthPolicies.NEGOTIATE); params.setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPreferences); AuthChallengeProcessor authChallengeProcessor = new AuthChallengeProcessor(params); Map<String, String> dnsMappings = new HashMap<String, String>(); dnsMappings.put("es.build.elastic.co", "127.0.0.1"); TestMethod method = new TestMethod(); method.setHeaders(new Header[]{new Header("WWW-Authenticate", "Negotiate")}); method.setURI(new org.apache.commons.httpclient.URI("http", null, "es.build.elastic.co", 9200)); Credentials credentials = new SpnegoCredentials(HadoopUserProvider.create(new TestSettings()), "HTTP/[email protected]"); // Parse Challenge Map challenges = AuthChallengeParser.parseChallenges(method.getResponseHeaders("WWW-Authenticate")); assertThat(challenges.isEmpty(), not(true)); assertThat(challenges.containsKey("negotiate"), is(true)); assertThat(challenges.get("negotiate"), is("Negotiate")); AuthScheme scheme = authChallengeProcessor.processChallenge(method.getHostAuthState(), challenges); assertNotNull(scheme); assertThat(scheme, instanceOf(SpnegoAuthScheme.class)); method.getHostAuthState().setAuthAttempted(true); // Execute Auth Header[] authHeaders = method.getRequestHeaders("Authorization"); for (Header authHeader : authHeaders) { if (authHeader.isAutogenerated()) { method.removeRequestHeader(authHeader); } } AuthState authState = method.getHostAuthState(); AuthScheme authScheme = authState.getAuthScheme(); assertNotNull(authScheme); assertThat(authScheme.isConnectionBased(), is(not(true))); // Replace scheme with test harness scheme authScheme = new TestScheme(dnsMappings); String authString = authScheme.authenticate(credentials, method); assertNotNull(authString); assertThat(authString, startsWith("Negotiate ")); method.addRequestHeader(new Header("Authorization", authString, true)); return null; } }); }
Example #29
Source File: AuthenticatedUrl.java From jrpip with Apache License 2.0 | 4 votes |
public AuthenticatedUrl(URL url, Credentials credentials, Cookie[] cookies) { this.url = url; this.credentials = credentials; this.cookies = cookies; }
Example #30
Source File: CustomNegotiateScheme.java From httpclientAuthHelper with Apache License 2.0 | 4 votes |
/** * Produces Negotiate authorization string based on token created by * processChallenge. * * @param credentials Never used be the Negotiate scheme but must be provided to * satisfy common-httpclient API. Credentials from JAAS will be used insted. * @param method The method being authenticated * * @throws org.apache.commons.httpclient.auth.AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return an Negotiate authorization string * * @since 3.0 */ public synchronized String authenticate( Credentials credentials, HttpMethod method ) throws AuthenticationException { LOG.info("enter CustomNegotiateScheme.authenticate(Credentials, HttpMethod)"); if (state == UNINITIATED) { throw new IllegalStateException( "Negotiation authentication process has not been initiated"); } try { try { if (context == null) { LOG.info("host: " + method.getURI().getHost()); init(method.getURI().getHost(), (UsernamePasswordCredentials) credentials); } } catch (org.apache.commons.httpclient.URIException urie) { LOG.severe(urie.getMessage()); state = FAILED; throw new AuthenticationException(urie.getMessage()); } // HTTP 1.1 issue: // Mutual auth will never complete do to 200 insted of 401 in // return from server. "state" will never reach ESTABLISHED // but it works anyway // token = context.initSecContext(token, 0, token.length); LOG.info("got token, sending " + token.length + " to server"); } catch (GSSException gsse) { LOG.severe(gsse.getMessage()); state = FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) { throw new InvalidCredentialsException(gsse.getMessage(), gsse); } if (gsse.getMajor() == GSSException.NO_CRED) { throw new CredentialsNotAvailableException(gsse.getMessage(), gsse); } if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) { throw new AuthChallengeException(gsse.getMessage(), gsse); } // other error throw new AuthenticationException(gsse.getMessage()); } return "Negotiate " + new String(new Base64(-1).encode(token)); }