Search in sources :

Example 86 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class TransportGuaranteeTestCase method checkGetURL.

/**
 * Check response on given url
 *
 * @param url
 * @param responseSubstring - if null we are checking response code only
 * @return
 * @throws Exception
 */
private boolean checkGetURL(String url, String responseSubstring, String user, String pass) throws Exception {
    log.trace("Checking URL=" + url);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY), new UsernamePasswordCredentials(user, pass));
    CloseableHttpClient httpClient;
    if (url.startsWith("https")) {
        httpClient = TestHttpClientUtils.getHttpsClient(credentialsProvider);
    } else {
        httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider).build();
    }
    HttpGet get = new HttpGet(url);
    HttpResponse hr;
    try {
        try {
            hr = httpClient.execute(get);
        } catch (Exception e) {
            if (responseSubstring == null) {
                return false;
            } else {
                // in case substring is defined, rethrow exception so, we can easier analyze the cause
                throw new Exception(e);
            }
        }
        int statusCode = hr.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            log.trace("statusCode not expected. statusCode=" + statusCode + ", URL=" + url);
            return false;
        }
        if (responseSubstring == null) {
            // this indicates that negative test had problems
            log.trace("statusCode==200 on URL=" + url);
            return true;
        }
        String response = EntityUtils.toString(hr.getEntity());
        if (response.indexOf(responseSubstring) != -1) {
            return true;
        } else {
            log.trace("Response doesn't contain expected substring (" + responseSubstring + ")");
            return false;
        }
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 87 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class WebSecurityBASICTestCase method makeCall.

@Override
protected void makeCall(String user, String pass, int expectedStatusCode) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()), new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build()) {
        HttpGet httpget = new HttpGet(url.toExternalForm() + "secured/");
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        StatusLine statusLine = response.getStatusLine();
        if (entity != null) {
            log.trace("Response content length: " + entity.getContentLength());
        }
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        if (200 == expectedStatusCode) {
            // check only in case authentication was successfull
            checkResponsecontent(EntityUtils.toString(entity), user, pass);
        }
        EntityUtils.consume(entity);
    }
}
Also used : StatusLine(org.apache.http.StatusLine) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) AuthScope(org.apache.http.auth.AuthScope) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Example 88 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class Utils method makeHttpCallWithFallback.

/**
 * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using SPNEGO first - if it fails,
 * FORM is used.
 *
 * @param contextUrl
 * @param page
 * @param user
 * @param pass
 * @param expectedStatusCode
 * @return
 * @throws IOException
 * @throws URISyntaxException
 * @throws PrivilegedActionException
 * @throws LoginException
 */
public static String makeHttpCallWithFallback(final String contextUrl, final String page, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.trace("Requesting URL: " + url);
    String unauthorizedPageBody = null;
    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
    final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).setRedirectStrategy(REDIRECT_STRATEGY).setConnectionManager(new BasicHttpClientConnectionManager()).build();
    try {
        final HttpGet httpGet = new HttpGet(url);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
        LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        unauthorizedPageBody = EntityUtils.toString(response.getEntity());
        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {

            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } catch (LoginException e) {
        assertNotNull(unauthorizedPageBody);
        assertTrue(unauthorizedPageBody.contains("j_security_check"));
        HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("j_username", user));
        nameValuePairs.add(new BasicNameValuePair("j_password", pass));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        final HttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpClient.close();
        // reset login configuration
        krb5Configuration.resetConfiguration();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpGet(org.apache.http.client.methods.HttpGet) LoginContext(javax.security.auth.login.LoginContext) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) ArrayList(java.util.ArrayList) List(java.util.List) BasicHttpClientConnectionManager(org.apache.http.impl.conn.BasicHttpClientConnectionManager) HashSet(java.util.HashSet) JBossNegotiateSchemeFactory(org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) NameValuePair(org.apache.http.NameValuePair) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) ClientProtocolException(org.apache.http.client.ClientProtocolException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) LoginException(javax.security.auth.login.LoginException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) LoginException(javax.security.auth.login.LoginException) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider)

Example 89 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.

the class Utils method makeCallWithKerberosAuthn.

/**
 * Returns response body for the given URL request as a String. It also checks if the returned HTTP status code is the
 * expected one. If the server returns {@link HttpServletResponse#SC_UNAUTHORIZED} and an username is provided, then the
 * given user is authenticated against Kerberos and a new request is executed under the new subject.
 *
 * @param uri URI to which the request should be made
 * @param user Username
 * @param pass Password
 * @param expectedStatusCode expected status code returned from the requested server
 * @return HTTP response body
 * @throws IOException
 * @throws URISyntaxException
 * @throws PrivilegedActionException
 * @throws LoginException
 */
public static String makeCallWithKerberosAuthn(final URI uri, final String user, final String pass, final int expectedStatusCode) throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    LOGGER.trace("Requesting URI: " + uri);
    Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.SPNEGO, new JBossNegotiateSchemeFactory(true)).build();
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());
    final Krb5LoginConfiguration krb5Configuration = new Krb5LoginConfiguration(getLoginConfiguration());
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).build()) {
        final HttpGet httpGet = new HttpGet(uri);
        final HttpResponse response = httpClient.execute(httpGet);
        int statusCode = response.getStatusLine().getStatusCode();
        if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
            assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
            return EntityUtils.toString(response.getEntity());
        }
        final HttpEntity entity = response.getEntity();
        final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
        assertTrue("WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
        final Set<String> authnHeaderValues = new HashSet<String>();
        for (final Header header : authnHeaders) {
            authnHeaderValues.add(header.getValue());
        }
        assertTrue("WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
        }
        if (entity != null)
            EntityUtils.consume(entity);
        // Use our custom configuration to avoid reliance on external config
        Configuration.setConfiguration(krb5Configuration);
        // 1. Authenticate to Kerberos.
        final LoginContext lc = loginWithKerberos(krb5Configuration, user, pass);
        // 2. Perform the work as authenticated Subject.
        final String responseBody = Subject.doAs(lc.getSubject(), new PrivilegedExceptionAction<String>() {

            public String run() throws Exception {
                final HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
                assertEquals("Unexpected status code returned after the authentication.", expectedStatusCode, statusCode);
                return EntityUtils.toString(response.getEntity());
            }
        });
        lc.logout();
        return responseBody;
    } finally {
        krb5Configuration.resetConfiguration();
    }
}
Also used : JBossNegotiateSchemeFactory(org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) ClientProtocolException(org.apache.http.client.ClientProtocolException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) LoginException(javax.security.auth.login.LoginException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) LoginContext(javax.security.auth.login.LoginContext) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) HashSet(java.util.HashSet)

Example 90 with CredentialsProvider

use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project weixin-java-tools by chanjarster.

the class WxCpServiceImpl method setWxCpConfigStorage.

public void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider) {
    this.wxCpConfigStorage = wxConfigProvider;
    String http_proxy_host = wxCpConfigStorage.getHttp_proxy_host();
    int http_proxy_port = wxCpConfigStorage.getHttp_proxy_port();
    String http_proxy_username = wxCpConfigStorage.getHttp_proxy_username();
    String http_proxy_password = wxCpConfigStorage.getHttp_proxy_password();
    if (StringUtils.isNotBlank(http_proxy_host)) {
        // 使用代理服务器
        if (StringUtils.isNotBlank(http_proxy_username)) {
            // 需要用户认证的代理服务器
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(http_proxy_host, http_proxy_port), new UsernamePasswordCredentials(http_proxy_username, http_proxy_password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            // 无需用户认证的代理服务器
            httpClient = HttpClients.createDefault();
        }
        httpProxy = new HttpHost(http_proxy_host, http_proxy_port);
    } else {
        httpClient = HttpClients.createDefault();
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

CredentialsProvider (org.apache.http.client.CredentialsProvider)271 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)223 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)201 AuthScope (org.apache.http.auth.AuthScope)138 HttpHost (org.apache.http.HttpHost)104 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)73 HttpGet (org.apache.http.client.methods.HttpGet)62 BasicScheme (org.apache.http.impl.auth.BasicScheme)49 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)48 HttpResponse (org.apache.http.HttpResponse)45 Test (org.junit.Test)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)41 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)40 IOException (java.io.IOException)39 URI (java.net.URI)36 Credentials (org.apache.http.auth.Credentials)36 AuthCache (org.apache.http.client.AuthCache)33 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)33 HttpClient (org.apache.http.client.HttpClient)31 RequestConfig (org.apache.http.client.config.RequestConfig)29