Search in sources :

Example 1 with AudienceRestrictionType

use of org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType in project keycloak by keycloak.

the class ClientTokenExchangeSAML2Test method testExchangeToSAML2EncryptedAssertion.

@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2EncryptedAssertion() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);
    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));
    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);
    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_ENCRYPTED_TARGET, "client-exchanger", "secret", params);
        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");
        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());
        // Decrypt assertion
        Document assertionDoc = DocumentUtil.getDocument(assertionXML);
        Element assertionElement = XMLEncryptionUtil.decryptElementInDocument(assertionDoc, privateKeyFromString(ENCRYPTION_PRIVATE_KEY));
        Assert.assertFalse(AssertionUtil.isSignedElement(assertionElement));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement);
        // Expires
        Assert.assertEquals(30, response.getExpiresIn());
        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_ENCRYPTED_TARGET, aud.getAudience().get(0).toString());
        // NameID
        Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());
        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) HashMap(java.util.HashMap) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) Element(org.w3c.dom.Element) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Document(org.w3c.dom.Document) AccessToken(org.keycloak.representations.AccessToken) List(java.util.List) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 2 with AudienceRestrictionType

use of org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType in project keycloak by keycloak.

the class ClientTokenExchangeSAML2Test method testExchangeToSAML2SignedAssertion.

@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2SignedAssertion() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);
    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "user", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "user");
    Assert.assertTrue(token.getRealmAccess() == null || !token.getRealmAccess().isUserInRole("example"));
    Map<String, String> params = new HashMap<>();
    params.put(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE);
    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_TARGET, "client-exchanger", "secret", params);
        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");
        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());
        // Verify assertion
        Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement();
        Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement);
        Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString(REALM_PUBLIC_KEY)));
        // Expires
        Assert.assertEquals(60, response.getExpiresIn());
        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString());
        // NameID
        Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());
        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_TARGET, "legal", "secret", params);
        String exchangedTokenString = response.getAccessToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");
        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, response.getIssuedTokenType());
        // Verify assertion
        Element assertionElement = DocumentUtil.getDocument(assertionXML).getDocumentElement();
        Assert.assertTrue(AssertionUtil.isSignedElement(assertionElement));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionElement);
        Assert.assertTrue(AssertionUtil.isSignatureValid(assertionElement, publicKeyFromString(REALM_PUBLIC_KEY)));
        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString());
        // NameID
        Assert.assertEquals("user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());
        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
    {
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_TARGET, "illegal", "secret", params);
        Assert.assertEquals(403, response.getStatusCode());
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) HashMap(java.util.HashMap) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) Element(org.w3c.dom.Element) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) AccessToken(org.keycloak.representations.AccessToken) List(java.util.List) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 3 with AudienceRestrictionType

use of org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType in project keycloak by keycloak.

the class SAMLConditionsParser method processSubElement.

@Override
protected void processSubElement(XMLEventReader xmlEventReader, ConditionsType target, SAMLAssertionQNames element, StartElement elementDetail) throws ParsingException {
    switch(element) {
        case AUDIENCE_RESTRICTION:
            AudienceRestrictionType audienceRestriction = SAMLAudienceRestrictionParser.getInstance().parse(xmlEventReader);
            target.addCondition(audienceRestriction);
            break;
        case ONE_TIME_USE:
            OneTimeUseType oneTimeUseCondition = new OneTimeUseType();
            target.addCondition(oneTimeUseCondition);
            break;
        case PROXY_RESTRICTION:
            ProxyRestrictionType proxyRestriction = SAMLProxyRestrictionParser.getInstance().parse(xmlEventReader);
            target.addCondition(proxyRestriction);
            break;
        default:
            throw LOGGER.parserUnknownTag(StaxParserUtil.getElementName(elementDetail), elementDetail.getLocation());
    }
}
Also used : OneTimeUseType(org.keycloak.dom.saml.v2.assertion.OneTimeUseType) ProxyRestrictionType(org.keycloak.dom.saml.v2.assertion.ProxyRestrictionType) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType)

Example 4 with AudienceRestrictionType

use of org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType in project keycloak by keycloak.

the class KcSamlIdPInitiatedSsoTest method assertAudience.

private void assertAudience(ResponseType resp, String expectedAudience) throws Exception {
    AssertionType a = AssertionUtil.getAssertion(null, resp, null);
    assertThat(a, notNullValue());
    assertThat(a.getConditions(), notNullValue());
    assertThat(a.getConditions().getConditions(), notNullValue());
    assertThat(a.getConditions().getConditions(), hasSize(greaterThan(0)));
    assertThat(a.getConditions().getConditions().get(0), instanceOf(AudienceRestrictionType.class));
    AudienceRestrictionType ar = (AudienceRestrictionType) a.getConditions().getConditions().get(0);
    assertThat(ar.getAudience(), contains(URI.create(expectedAudience)));
}
Also used : AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType)

Example 5 with AudienceRestrictionType

use of org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType in project keycloak by keycloak.

the class AudienceProtocolMappersTest method testExpectedAudiences.

public void testExpectedAudiences(String... audiences) {
    SAMLDocumentHolder document = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME), SAML_CLIENT_ID_EMPLOYEE_2, SAML_ASSERTION_CONSUMER_URL_EMPLOYEE_2, SamlClient.Binding.POST).build().login().user(bburkeUser).build().getSamlResponse(SamlClient.Binding.POST);
    Assert.assertNotNull(document.getSamlObject());
    Assert.assertThat(document.getSamlObject(), Matchers.isSamlResponse(JBossSAMLURIConstants.STATUS_SUCCESS));
    Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions());
    Assert.assertThat(((ResponseType) document.getSamlObject()).getAssertions().size(), greaterThan(0));
    Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0));
    Assert.assertNotNull(((ResponseType) document.getSamlObject()).getAssertions().get(0).getAssertion());
    AudienceRestrictionType audience = ((ResponseType) document.getSamlObject()).getAssertions().get(0).getAssertion().getConditions().getConditions().stream().filter(AudienceRestrictionType.class::isInstance).map(AudienceRestrictionType.class::cast).findFirst().orElse(null);
    Assert.assertNotNull(audience);
    Assert.assertNotNull(audience.getAudience());
    List<String> values = audience.getAudience().stream().map(uri -> uri.toString()).collect(Collectors.toList());
    Assert.assertThat(values, containsInAnyOrder(audiences));
}
Also used : ClientAttributeUpdater(org.keycloak.testsuite.updaters.ClientAttributeUpdater) ProtocolMappersUpdater(org.keycloak.testsuite.updaters.ProtocolMappersUpdater) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) SAMLAudienceProtocolMapper(org.keycloak.protocol.saml.mappers.SAMLAudienceProtocolMapper) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) AUTH_SERVER_SSL_REQUIRED(org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SSL_REQUIRED) After(org.junit.After) SAMLAudienceResolveProtocolMapper(org.keycloak.protocol.saml.mappers.SAMLAudienceResolveProtocolMapper) SamlClient(org.keycloak.testsuite.util.SamlClient) RoleRepresentation(org.keycloak.representations.idm.RoleRepresentation) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) Before(org.junit.Before) ApiUtil(org.keycloak.testsuite.admin.ApiUtil) AUTH_SERVER_SCHEME(org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_SCHEME) Matchers(org.keycloak.testsuite.util.Matchers) JBossSAMLURIConstants(org.keycloak.saml.common.constants.JBossSAMLURIConstants) RoleScopeUpdater(org.keycloak.testsuite.updaters.RoleScopeUpdater) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) IOException(java.io.IOException) Test(org.junit.Test) Collectors(java.util.stream.Collectors) AUTH_SERVER_PORT(org.keycloak.testsuite.util.ServerURLs.AUTH_SERVER_PORT) List(java.util.List) Response(javax.ws.rs.core.Response) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) UserAttributeUpdater(org.keycloak.testsuite.updaters.UserAttributeUpdater) RoleMapperTest.createSamlProtocolMapper(org.keycloak.testsuite.saml.RoleMapperTest.createSamlProtocolMapper) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Assert(org.junit.Assert) Collections(java.util.Collections) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) SAMLDocumentHolder(org.keycloak.saml.processing.core.saml.v2.common.SAMLDocumentHolder) SamlClientBuilder(org.keycloak.testsuite.util.SamlClientBuilder) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType)

Aggregations

AudienceRestrictionType (org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType)12 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)8 List (java.util.List)7 Test (org.junit.Test)7 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)7 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)6 UncaughtServerErrorExpected (org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)6 OAuthClient (org.keycloak.testsuite.util.OAuthClient)6 HashMap (java.util.HashMap)5 AccessToken (org.keycloak.representations.AccessToken)5 Element (org.w3c.dom.Element)5 OneTimeUseType (org.keycloak.dom.saml.v2.assertion.OneTimeUseType)4 Response (javax.ws.rs.core.Response)2 AuthnStatementType (org.keycloak.dom.saml.v2.assertion.AuthnStatementType)2 ConditionAbstractType (org.keycloak.dom.saml.v2.assertion.ConditionAbstractType)2 ConditionsType (org.keycloak.dom.saml.v2.assertion.ConditionsType)2 ProxyRestrictionType (org.keycloak.dom.saml.v2.assertion.ProxyRestrictionType)2 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)2 Document (org.w3c.dom.Document)2 IOException (java.io.IOException)1