private void doPreemptiveAuth( final HttpHost host, final AuthScheme authScheme, final AuthState authState, final CredentialsProvider credsProvider) { String schemeName = authScheme.getSchemeName(); if (this.log.isDebugEnabled()) { this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host); } AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setState(AuthProtocolState.SUCCESS); authState.update(authScheme, creds); } else { this.log.debug("No credentials for preemptive authentication"); } }
/** * Produces basic authorization header for the given set of {@link Credentials}. * * @param credentials The set of credentials to be used for authentication * @param request The request being authenticated * @throws InvalidCredentialsException if authentication credentials are not * valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a basic authorization string */ @Override public Header authenticate( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (credentials == null) { throw new IllegalArgumentException("Credentials may not be null"); } if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } String charset = AuthParams.getCredentialCharset(request.getParams()); return authenticate(credentials, charset, isProxy()); }
/** * Find matching {@link Credentials credentials} for the given authentication scope. * * @param map the credentials hash map * @param authscope the {@link AuthScope authentication scope} * @return the credentials * */ private static Credentials matchCredentials( final Map<AuthScope, Credentials> map, final AuthScope authscope) { // see if we get a direct hit Credentials creds = map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; for (AuthScope current: map.keySet()) { int factor = authscope.match(current); if (factor > bestMatchFactor) { bestMatchFactor = factor; bestMatch = current; } } if (bestMatch != null) { creds = map.get(bestMatch); } } return creds; }
public void setProxy(String proxyHost, Integer proxyPort, Credentials credentials) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; if (this.proxyHost.length() > 0 && !this.proxyPort.equals(0)) { HttpClientBuilder clientBuilder = HttpClients.custom() .useSystemProperties() .setProxy(new HttpHost(proxyHost, proxyPort, "http")); if (credentials != null) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials); clientBuilder.setDefaultCredentialsProvider(credsProvider); Loggers.SERVER.debug("MsTeamsNotification ::using proxy credentials " + credentials.getUserPrincipal().getName()); } this.client = clientBuilder.build(); } }
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute("http.auth.target-scope"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute("http.auth" + ".credentials-provider"); HttpHost targetHost = (HttpHost) context.getAttribute("http.target_host"); if (authState.getAuthScheme() == null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName (), targetHost.getPort())); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } }
private SystemDefaultHttpClient getHttpClient() { final SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient(); httpClient.getAuthSchemes().register(AuthPolicy.SPNEGO, new SPNegoSchemeFactory(true)); Credentials use_jaas_creds = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; httpClient.getCredentialsProvider().setCredentials( AuthScope.ANY, use_jaas_creds); return httpClient; }
public static HttpClient build(byte[] token) { HttpClientBuilder builder = HttpClientBuilder.create(); Lookup<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, new CollaredSPNegoSchemeFactory(token)).build(); builder.setDefaultAuthSchemeRegistry(authSchemeRegistry); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), new Credentials() { @Override public Principal getUserPrincipal() { return null; } @Override public String getPassword() { return null; } }); builder.setDefaultCredentialsProvider(credentialsProvider); return builder.build(); }
@Test public void buildClientWithCredentials() throws Exception { final Config config = ConfigFactory.parseString("{ url = \"http://example.com\", output.path = /home/user/downloads, saveAs = \"%1$s.pdf\", " + "credentials { username = theUser, password = thePassword } }"); CloseableHttpClient client = FileDownload.buildClient(config); Field field = client.getClass().getDeclaredField("credentialsProvider"); field.setAccessible(true); Object provider = field.get(client); assertThat(provider).isInstanceOf(BasicCredentialsProvider.class); BasicCredentialsProvider basicProvider = (BasicCredentialsProvider) provider; Credentials credentials = basicProvider.getCredentials(new AuthScope(null, -1)); assertThat(credentials.getUserPrincipal().getName()).isEqualTo("theUser"); assertThat(credentials.getPassword()).isEqualTo("thePassword"); }
public static String getResponseAsString(String url) throws IOException { String result = null; try (CloseableHttpResponse yearResponse = NetUtils.openConnection(url, (Credentials) null)) { switch (yearResponse.getStatusLine().getStatusCode()) { case 200: result = EntityUtils.toString(yearResponse.getEntity()); break; case 401: Logger.getRootLogger().info("The supplied credentials are invalid!"); break; default: Logger.getRootLogger().info("The request was not successful. Reason: %s", yearResponse.getStatusLine().getReasonPhrase()); break; } } return result; }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.setAuthScheme(authScheme); authState.setCredentials(creds); } } }
private void doPreemptiveAuth( final HttpHost host, final AuthScheme authScheme, final AuthStateHC4 authState, final CredentialsProvider credsProvider) { final String schemeName = authScheme.getSchemeName(); if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Re-using cached '" + schemeName + "' auth scheme for " + host); } final AuthScope authScope = new AuthScope(host.getHostName(), host.getPort(), AuthScope.ANY_REALM, schemeName); final Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) { authState.setState(AuthProtocolState.CHALLENGED); } else { authState.setState(AuthProtocolState.SUCCESS); } authState.update(authScheme, creds); } else { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "No credentials for preemptive authentication"); } } }
/** * Produces a digest authorization string for the given set of * {@link Credentials}, method name and URI. * * @param credentials A set of credentials to be used for athentication * @param request The request being authenticated * * @throws org.apache.http.auth.InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a digest authorization string */ @Override public Header authenticate( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { Args.notNull(credentials, "Credentials"); Args.notNull(request, "HTTP request"); if (getParameter("realm") == null) { throw new AuthenticationException("missing realm in challenge"); } if (getParameter("nonce") == null) { throw new AuthenticationException("missing nonce in challenge"); } // Add method name and request-URI to the parameter map getParameters().put("methodname", request.getRequestLine().getMethod()); getParameters().put("uri", request.getRequestLine().getUri()); final String charset = getParameter("charset"); if (charset == null) { getParameters().put("charset", getCredentialsCharset(request)); } return createDigestHeader(credentials, request); }
/** * Find matching {@link Credentials credentials} for the given authentication scope. * * @param map the credentials hash map * @param authscope the {@link AuthScope authentication scope} * @return the credentials * */ private static Credentials matchCredentials( final Map<AuthScope, Credentials> map, final AuthScope authscope) { // see if we get a direct hit Credentials creds = map.get(authscope); if (creds == null) { // Nope. // Do a full scan int bestMatchFactor = -1; AuthScope bestMatch = null; for (final AuthScope current: map.keySet()) { final int factor = authscope.match(current); if (factor > bestMatchFactor) { bestMatchFactor = factor; bestMatch = current; } } if (bestMatch != null) { creds = map.get(bestMatch); } } return creds; }
/** * Tests that the client will stop connecting to the server if * the server still keep asking for a valid ticket. */ @Test public void testDontTryToAuthenticateEndlessly() throws Exception { this.serverBootstrap.registerHandler("*", new PleaseNegotiateService()); final HttpHost target = start(); final AuthSchemeProvider nsf = new NegotiateSchemeProviderWithMockGssManager(); final CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); final Credentials use_jaas_creds = new UseJaasCredentials(); credentialsProvider.setCredentials(new AuthScope(null, -1, null), use_jaas_creds); final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.SPNEGO, nsf) .build(); this.httpclient = HttpClients.custom() .setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credentialsProvider) .build(); final String s = "/path"; final HttpGet httpget = new HttpGet(s); final HttpResponse response = this.httpclient.execute(target, httpget); EntityUtils.consume(response.getEntity()); Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode()); }
/** * {@inheritDoc} */ @Override public Credentials getCredentials(final AuthScope authscope) { // iterate over all active proxy configurations at the moment of getting the credential for (final ServiceRegistration registration : registeredConfigurations.values()) { final Object proxyConfigurationObject = bundleContext.getService(registration.getReference()); if (proxyConfigurationObject != null) { final ProxyConfiguration proxyConfiguration = (ProxyConfiguration) proxyConfigurationObject; if (proxyConfiguration.isEnabled()) { final AuthScope actual = new AuthScope(proxyConfiguration.getHostname(), proxyConfiguration.getPort()); if (authscope.match(actual) >= 12) { return new UsernamePasswordCredentials(proxyConfiguration.getUsername(), proxyConfiguration.getPassword()); } } } } // credentials no longer available! return null; }
/** * Configure proxy for this connection with a ProxySettings object * * @param proxy * Proxy configuration file to use */ public void setProxy(ProxySettings proxy) { // If the proxy is set: if (proxy.isEnabled()) { HttpHost proxyConnection = new HttpHost(proxy.getServer(), proxy.getPort(), "http"); // Proxy auth is handled like http authentication if (proxy.isAuth()) { AuthScope proxyScope = new AuthScope(proxy.getServer(), proxy.getPort()); Credentials proxyCreds = new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword()); this.httpclient.getCredentialsProvider().setCredentials(proxyScope, proxyCreds); } // Register the proxy server with the http client handler this.httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyConnection); } }
private HttpClientContext getHttpContext() { HttpClientContext context = HttpClientContext.create(); BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); Credentials credentials = new Credentials() { public String getPassword() { return null; } public Principal getUserPrincipal() { return null; } }; credentialsProvider.setCredentials(new AuthScope(null, -1, null), credentials); context.setCredentialsProvider(credentialsProvider); return context; }
@Override public void process(HttpRequest httpRequest, HttpContext httpContext) throws HttpException, IOException { AuthState authState = (AuthState) httpContext.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) httpContext.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) httpContext .getAttribute(HttpClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) httpContext.getAttribute(HttpClientContext.HTTP_TARGET_HOST); if (authScheme != null) { Credentials creds = credsProvider .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, creds); } } }
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); // If no auth scheme avaialble yet, try to initialize it preemptively if (authState.getAuthScheme() == null) { AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth"); CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(HttpClientContext.CREDS_PROVIDER); if (authScheme != null) { Credentials creds = credsProvider.getCredentials(AuthScope.ANY); if (creds == null) { throw new HttpException("No credentials for preemptive authentication"); } authState.update(authScheme, creds); } } }
private void doPreemptiveAuth( final HttpHost host, final AuthScheme authScheme, final AuthState authState, final CredentialsProvider credsProvider) { final String schemeName = authScheme.getSchemeName(); if (this.log.isDebugEnabled()) { this.log.debug("Re-using cached '" + schemeName + "' auth scheme for " + host); } final AuthScope authScope = new AuthScope(host, AuthScope.ANY_REALM, schemeName); final Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { if ("BASIC".equalsIgnoreCase(authScheme.getSchemeName())) { authState.setState(AuthProtocolState.CHALLENGED); } else { authState.setState(AuthProtocolState.SUCCESS); } authState.update(authScheme, creds); } else { this.log.debug("No credentials for preemptive authentication"); } }
@Test public void testDigestAuthenticationWithDefaultCreds() throws Exception { final String challenge = "Digest realm=\"realm1\", nonce=\"f2a3f18799759d4f1a1c068b92b573cb\""; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpRequest request = new BasicHttpRequest("Simple", "/"); final Credentials cred = new UsernamePasswordCredentials("username","password"); final DigestScheme authscheme = new DigestScheme(); final HttpContext context = new BasicHttpContext(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); Assert.assertTrue(authscheme.isComplete()); Assert.assertFalse(authscheme.isConnectionBased()); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/", table.get("uri")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); Assert.assertEquals("e95a7ddf37c2eab009568b1ed134f89a", table.get("response")); }
@Before public void setUp() throws Exception { this.defltAuthStrategy = Mockito.mock(AuthenticationStrategy.class); this.authState = new AuthState(); this.authScheme = Mockito.mock(ContextAwareAuthScheme.class); Mockito.when(this.authScheme.getSchemeName()).thenReturn("Basic"); Mockito.when(this.authScheme.isComplete()).thenReturn(Boolean.TRUE); this.context = new BasicHttpContext(); this.defaultHost = new HttpHost("localhost", 80); this.context.setAttribute(HttpCoreContext.HTTP_TARGET_HOST, this.defaultHost); this.credentials = Mockito.mock(Credentials.class); this.credentialsProvider = new BasicCredentialsProvider(); this.credentialsProvider.setCredentials(AuthScope.ANY, this.credentials); this.context.setAttribute(HttpClientContext.CREDS_PROVIDER, this.credentialsProvider); this.authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register("basic", new BasicSchemeFactory()) .register("digest", new DigestSchemeFactory()) .register("ntlm", new NTLMSchemeFactory()).build(); this.context.setAttribute(HttpClientContext.AUTHSCHEME_REGISTRY, this.authSchemeRegistry); this.authCache = Mockito.mock(AuthCache.class); this.context.setAttribute(HttpClientContext.AUTH_CACHE, this.authCache); this.httpAuthenticator = new HttpAuthenticator(); }
@Test public void testDigestAuthenticationWithSHA() throws Exception { final String challenge = "Digest realm=\"realm1\", " + "nonce=\"f2a3f18799759d4f1a1c068b92b573cb\", " + "algorithm=SHA"; final Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge); final HttpRequest request = new BasicHttpRequest("Simple", "/"); final Credentials cred = new UsernamePasswordCredentials("username","password"); final HttpContext context = new BasicHttpContext(); final DigestScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); final Header authResponse = authscheme.authenticate(cred, request, context); final Map<String, String> table = parseAuthResponse(authResponse); Assert.assertEquals("username", table.get("username")); Assert.assertEquals("realm1", table.get("realm")); Assert.assertEquals("/", table.get("uri")); Assert.assertEquals("f2a3f18799759d4f1a1c068b92b573cb", table.get("nonce")); Assert.assertEquals("8769e82e4e28ecc040b969562b9050580c6d186d", table.get("response")); }
@Test public void testAuthChallengeStateOneOptions() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); this.authState.setState(AuthProtocolState.CHALLENGED); final LinkedList<AuthOption> authOptions = new LinkedList<AuthOption>(); authOptions.add(new AuthOption(this.authScheme, this.credentials)); this.authState.update(authOptions); Mockito.when(this.authScheme.authenticate( Mockito.any(Credentials.class), Mockito.any(HttpRequest.class), Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff")); this.httpAuthenticator.generateAuthResponse(request, authState, context); Assert.assertSame(this.authScheme, this.authState.getAuthScheme()); Assert.assertSame(this.credentials, this.authState.getCredentials()); Assert.assertNull(this.authState.getAuthOptions()); Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP)); Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context); }
@Test public void testAuthSuccess() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); this.authState.setState(AuthProtocolState.SUCCESS); this.authState.update(this.authScheme, this.credentials); Mockito.when(this.authScheme.isConnectionBased()).thenReturn(Boolean.FALSE); Mockito.when(this.authScheme.authenticate( Mockito.any(Credentials.class), Mockito.any(HttpRequest.class), Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff")); this.httpAuthenticator.generateAuthResponse(request, authState, context); Assert.assertSame(this.authScheme, this.authState.getAuthScheme()); Assert.assertSame(this.credentials, this.authState.getCredentials()); Assert.assertNull(this.authState.getAuthOptions()); Assert.assertTrue(request.containsHeader(AUTH.WWW_AUTH_RESP)); Mockito.verify(this.authScheme).authenticate(this.credentials, request, this.context); }
@Test public void testAuthSuccessConnectionBased() throws Exception { final HttpRequest request = new BasicHttpRequest("GET", "/"); this.authState.setState(AuthProtocolState.SUCCESS); this.authState.update(this.authScheme, this.credentials); Mockito.when(this.authScheme.isConnectionBased()).thenReturn(Boolean.TRUE); Mockito.when(this.authScheme.authenticate( Mockito.any(Credentials.class), Mockito.any(HttpRequest.class), Mockito.any(HttpContext.class))).thenReturn(new BasicHeader(AUTH.WWW_AUTH_RESP, "stuff")); this.httpAuthenticator.generateAuthResponse(request, authState, context); Assert.assertFalse(request.containsHeader(AUTH.WWW_AUTH_RESP)); Mockito.verify(this.authScheme, Mockito.never()).authenticate( Mockito.any(Credentials.class), Mockito.any(HttpRequest.class), Mockito.any(HttpContext.class)); }
/** * @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} */ @Deprecated public Header authenticate( final Credentials credentials, final HttpRequest request ) throws AuthenticationException { return authenticate(credentials, request, null); }
@SuppressWarnings("deprecation") private Header authenticate( final AuthScheme authScheme, final Credentials creds, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (authScheme == null) { throw new IllegalStateException("Auth state object is null"); } if (authScheme instanceof ContextAwareAuthScheme) { return ((ContextAwareAuthScheme) authScheme).authenticate(creds, request, context); } else { return authScheme.authenticate(creds, request); } }
/** * Produces a digest authorization string for the given set of * {@link Credentials}, method name and URI. * * @param credentials A set of credentials to be used for athentication * @param request The request being authenticated * * @throws org.apache.http.auth.InvalidCredentialsException if authentication credentials * are not valid or not applicable for this authentication scheme * @throws AuthenticationException if authorization string cannot * be generated due to an authentication failure * * @return a digest authorization string */ @Override public Header authenticate( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (credentials == null) { throw new IllegalArgumentException("Credentials may not be null"); } if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (getParameter("realm") == null) { throw new AuthenticationException("missing realm in challenge"); } if (getParameter("nonce") == null) { throw new AuthenticationException("missing nonce in challenge"); } // Add method name and request-URI to the parameter map getParameters().put("methodname", request.getRequestLine().getMethod()); getParameters().put("uri", request.getRequestLine().getUri()); String charset = getParameter("charset"); if (charset == null) { charset = AuthParams.getCredentialCharset(request.getParams()); getParameters().put("charset", charset); } return createDigestHeader(credentials, request); }
/** * Returns a basic <tt>Authorization</tt> header value for the given * {@link Credentials} and charset. * * @param credentials The credentials to encode. * @param charset The charset to use for encoding the credentials * * @return a basic authorization header */ public static Header authenticate( final Credentials credentials, final String charset, boolean proxy) { if (credentials == null) { throw new IllegalArgumentException("Credentials may not be null"); } if (charset == null) { throw new IllegalArgumentException("charset may not be null"); } StringBuilder tmp = new StringBuilder(); tmp.append(credentials.getUserPrincipal().getName()); tmp.append(":"); tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword()); byte[] base64password = Base64.encodeBase64( EncodingUtils.getBytes(tmp.toString(), charset)); CharArrayBuffer buffer = new CharArrayBuffer(32); if (proxy) { buffer.append(AUTH.PROXY_AUTH_RESP); } else { buffer.append(AUTH.WWW_AUTH_RESP); } buffer.append(": Basic "); buffer.append(base64password, 0, base64password.length); return new BufferedHeader(buffer); }
/** * @deprecated (4.2) Use {@link ContextAwareAuthScheme#authenticate(Credentials, HttpRequest, org.apache.http.protocol.HttpContext)} */ @Deprecated public Header authenticate( final Credentials credentials, final HttpRequest request) throws AuthenticationException { return authenticate(credentials, request, null); }
@SuppressWarnings("deprecation") public Header authenticate( final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { return authenticate(credentials, request); }
private static Principal getAuthPrincipal(final AuthState authState) { AuthScheme scheme = authState.getAuthScheme(); if (scheme != null && scheme.isComplete() && scheme.isConnectionBased()) { Credentials creds = authState.getCredentials(); if (creds != null) { return creds.getUserPrincipal(); } } return null; }
public void setCredentials( final AuthScope authscope, final Credentials credentials) { if (authscope == null) { throw new IllegalArgumentException("Authentication scope may not be null"); } credMap.put(authscope, credentials); }
public void process(final HttpRequest request, final HttpContext context) throws HttpException { final AuthState authState = (AuthState) context.getAttribute(HttpClientContext.TARGET_AUTH_STATE); if (authState.getAuthScheme() == null) { final CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(HttpClientContext.CREDS_PROVIDER); final HttpHost targetHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); final Credentials creds = credsProvider.getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort())); if (creds == null) { throw new HttpException("No creds provided for preemptive auth."); } authState.update(new BasicScheme(), creds); } }
@Test public void TestFullConfig(){ String expectedConfigDirectory = "."; ServerPaths serverPaths = mock(ServerPaths.class); when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); MsTeamsNotificationMainSettings whms = new MsTeamsNotificationMainSettings(server, serverPaths); whms.register(); whms.readFrom(getFullConfigElement()); String proxy = whms.getProxy(); MsTeamsNotificationProxyConfig whpc = whms.getProxyConfig(); assertTrue(proxy.equals(this.proxyHost)); assertTrue(whpc.getProxyHost().equals(this.proxyHost )); assertTrue(whpc.getProxyPort().equals(this.proxyPort)); assertTrue(whms.getToken().equals(this.token)); assertTrue(whms.getIconUrl().equals(this.iconUrl)); assertTrue(whms.getBotName().equals(this.botName)); assertTrue(whms.getShowBuildAgent()); assertTrue(whms.getShowElapsedBuildTime()); assertFalse(whms.getShowCommits()); assertEquals(15, whms.getMaxCommitsToDisplay()); assertTrue(whms.getShowFailureReason()); Credentials credentials = whpc.getCreds(); assertEquals("some-username", credentials.getUserPrincipal().getName()); assertEquals("some-password", credentials.getPassword()); }
/** * Construct httpclient with SSL protocol * * @param clientConfiguration the client configuration * @return {@code CloseableHttpClient} * @throws Exception */ public static CloseableHttpClient getHttpClient(ClientConfiguration clientConfiguration) throws Exception { if (clientConfiguration == null) { clientConfiguration = new ClientConfiguration(); } SSLConnectionSocketFactory sslSocketFactory = createSslConnectionSocketFactory(clientConfiguration); HttpClientBuilder builder = HttpClients.custom(); // set proxy String proxyHost = clientConfiguration.getProxyHost(); int proxyPort = clientConfiguration.getProxyPort(); if (!StringUtils.isEmpty(proxyHost) && proxyPort > 0) { HttpHost proxy = new HttpHost(proxyHost, proxyPort); builder.setProxy(proxy); String username = clientConfiguration.getProxyUserName(); String password = clientConfiguration.getProxyPassword(); if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); AuthScope authscope = new AuthScope(proxy); Credentials credentials = new UsernamePasswordCredentials(username, password); credentialsProvider.setCredentials(authscope, credentials); builder.setDefaultCredentialsProvider(credentialsProvider); } } builder.setUserAgent(VersionUtil.getDefaultUserAgent()); CloseableHttpClient httpclient = builder.setSSLSocketFactory(sslSocketFactory).build(); return httpclient; }