Search in sources :

Example 1 with JBossNegotiateSchemeFactory

use of org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory 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 2 with JBossNegotiateSchemeFactory

use of org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory 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)

Example 3 with JBossNegotiateSchemeFactory

use of org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory 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) List(java.util.List) ArrayList(java.util.ArrayList) 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) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) 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) Header(org.apache.http.Header) AuthScope(org.apache.http.auth.AuthScope) LoginException(javax.security.auth.login.LoginException) AuthSchemeProvider(org.apache.http.auth.AuthSchemeProvider)

Aggregations

AuthSchemeProvider (org.apache.http.auth.AuthSchemeProvider)3 AuthScope (org.apache.http.auth.AuthScope)3 CredentialsProvider (org.apache.http.client.CredentialsProvider)3 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 JBossNegotiateSchemeFactory (org.jboss.as.test.integration.security.common.negotiation.JBossNegotiateSchemeFactory)3 IOException (java.io.IOException)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 MalformedURLException (java.net.MalformedURLException)2 URISyntaxException (java.net.URISyntaxException)2 UnknownHostException (java.net.UnknownHostException)2 PrivilegedActionException (java.security.PrivilegedActionException)2 HashSet (java.util.HashSet)2 LoginContext (javax.security.auth.login.LoginContext)2 LoginException (javax.security.auth.login.LoginException)2 Header (org.apache.http.Header)2 HttpResponse (org.apache.http.HttpResponse)2 ProtocolException (org.apache.http.ProtocolException)2 HttpGet (org.apache.http.client.methods.HttpGet)2 URL (java.net.URL)1