Search in sources :

Example 21 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project wildfly by wildfly.

the class SAML2AttributeMappingTestCase method testPassUserPrincipalToAttributeManager.

/**
     * Tests IDP attribute mapping when passUserPrincipalToAttributeManager is set to "true". Automatic handling of redirections
     * is enabled for HTTP client used.
     *
     * @throws Exception
     */
@Test
public void testPassUserPrincipalToAttributeManager() throws Exception {
    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());
    try (final CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultAuthSchemeRegistry(authSchemeRegistry).setDefaultCredentialsProvider(credentialsProvider).setRedirectStrategy(Utils.REDIRECT_STRATEGY).build()) {
        String response = PicketLinkTestBase.makeCallWithKerberosAuthn(spUrl.toURI(), httpClient, "jduke", "theduke", 200);
        assertEquals("SP index page was not reached", SP_RESPONSE_BODY, response);
        response = PicketLinkTestBase.makeCall(new URL(spUrl.toString() + PrintAttributeServlet.SERVLET_PATH.substring(1)), httpClient, 200);
        assertEquals("cn attribute not stored", "Java Duke", response);
    }
}
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) NullHCCredentials(org.jboss.as.test.integration.security.common.NullHCCredentials) AuthScope(org.apache.http.auth.AuthScope) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URL(java.net.URL) Test(org.junit.Test)

Example 22 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider in project wildfly by wildfly.

the class BasicAuthenticationWebFailoverTestCase method test.

@Test
public void test(@ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1, @ArquillianResource(SecureServlet.class) @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2) throws IOException, URISyntaxException {
    CredentialsProvider provider = new BasicCredentialsProvider();
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    URI uri1 = SecureServlet.createURI(baseURL1);
    URI uri2 = SecureServlet.createURI(baseURL2);
    try {
        // Valid login, invalid role
        setCredentials(provider, "forbidden", "password", baseURL1, baseURL2);
        HttpResponse response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_FORBIDDEN, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        // Invalid login, valid role
        setCredentials(provider, "allowed", "bad", baseURL1, baseURL2);
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        // Valid login, valid role
        setCredentials(provider, "allowed", "password", baseURL1, baseURL2);
        String sessionId = null;
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertNotNull(response.getFirstHeader(SecureServlet.SESSION_ID_HEADER));
            sessionId = response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue();
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        undeploy(DEPLOYMENT_1);
        response = client.execute(new HttpGet(uri2));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
        deploy(DEPLOYMENT_1);
        response = client.execute(new HttpGet(uri1));
        try {
            Assert.assertEquals(HttpServletResponse.SC_OK, response.getStatusLine().getStatusCode());
            Assert.assertEquals(sessionId, response.getFirstHeader(SecureServlet.SESSION_ID_HEADER).getValue());
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}
Also used : BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) Test(org.junit.Test)

Example 23 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider 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 (// in case substring is defined, rethrow exception so, we can easier analyze the cause
            responseSubstring == null) // in case substring is defined, rethrow exception so, we can easier analyze the cause
            {
                return false;
            } else {
                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 24 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider 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());
        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 25 with BasicCredentialsProvider

use of org.apache.http.impl.client.BasicCredentialsProvider 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 (final 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) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) LoginException(javax.security.auth.login.LoginException) ProtocolException(org.apache.http.ProtocolException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) PrivilegedActionException(java.security.PrivilegedActionException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) 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)

Aggregations

BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)75 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)63 CredentialsProvider (org.apache.http.client.CredentialsProvider)48 AuthScope (org.apache.http.auth.AuthScope)41 HttpHost (org.apache.http.HttpHost)22 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)20 HttpResponse (org.apache.http.HttpResponse)16 HttpGet (org.apache.http.client.methods.HttpGet)16 HttpClient (org.apache.http.client.HttpClient)14 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)14 IOException (java.io.IOException)13 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)10 AuthCache (org.apache.http.client.AuthCache)9 RequestConfig (org.apache.http.client.config.RequestConfig)9 BasicAuthCache (org.apache.http.impl.client.BasicAuthCache)9 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)8 BasicScheme (org.apache.http.impl.auth.BasicScheme)8 Test (org.junit.Test)8 HttpEntity (org.apache.http.HttpEntity)6 AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)6