Search in sources :

Example 36 with AssertionType

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

the class ClientTokenExchangeSAML2Test method testExchangeToSAML2SignedAndEncryptedAssertion.

@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2SignedAndEncryptedAssertion() 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_AND_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());
        // Verify assertion
        Document assertionDoc = DocumentUtil.getDocument(assertionXML);
        Element assertionElement = XMLEncryptionUtil.decryptElementInDocument(assertionDoc, privateKeyFromString(ENCRYPTION_PRIVATE_KEY));
        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_AND_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 37 with AssertionType

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

the class ClientTokenExchangeSAML2Test method testDirectImpersonation.

@Test
@UncaughtServerErrorExpected
public void testDirectImpersonation() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);
    Client httpClient = AdminClientUtil.createResteasyClient();
    WebTarget exchangeUrl = httpClient.target(OAuthClient.AUTH_SERVER_ROOT).path("/realms").path(TEST).path("protocol/openid-connect/token");
    System.out.println("Exchange url: " + exchangeUrl.getUri().toString());
    // direct-legal can impersonate from token "user" to user "impersonated-user" and to "target" client
    {
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-legal", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user").param(OAuth2Constants.AUDIENCE, SAML_SIGNED_TARGET)));
        Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse accessTokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        String exchangedTokenString = accessTokenResponse.getToken();
        String assertionXML = new String(Base64Url.decode(exchangedTokenString), "UTF-8");
        // Verify issued_token_type
        Assert.assertEquals(OAuth2Constants.SAML2_TOKEN_TYPE, accessTokenResponse.getOtherClaims().get(OAuth2Constants.ISSUED_TOKEN_TYPE));
        // 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("impersonated-user", ((NameIDType) assertion.getSubject().getSubType().getBaseID()).getValue());
        // Role mapping
        List<String> roles = AssertionUtil.getRoles(assertion, null);
        Assert.assertTrue(roles.contains("example"));
    }
    // direct-public fails impersonation
    {
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-public", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user").param(OAuth2Constants.AUDIENCE, SAML_SIGNED_TARGET)));
        Assert.assertEquals(403, response.getStatus());
        response.close();
    }
    // direct-no-secret fails impersonation
    {
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-no-secret", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.REQUESTED_TOKEN_TYPE, OAuth2Constants.SAML2_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user").param(OAuth2Constants.AUDIENCE, SAML_SIGNED_TARGET)));
        Assert.assertTrue(response.getStatus() >= 400);
        response.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) AudienceRestrictionType(org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType) Element(org.w3c.dom.Element) List(java.util.List) WebTarget(javax.ws.rs.client.WebTarget) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) NameIDType(org.keycloak.dom.saml.v2.assertion.NameIDType) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 38 with AssertionType

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

the class ClientTokenExchangeSAML2Test method testImpersonation.

@Test
@UncaughtServerErrorExpected
public void testImpersonation() 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);
    // client-exchanger can impersonate from token "user" to user "impersonated-user" and to "target" client
    {
        params.put(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user");
        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)));
        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_SIGNED_TARGET, aud.getAudience().get(0).toString());
        // NameID
        Assert.assertEquals("impersonated-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) 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 39 with AssertionType

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

the class ClientTokenExchangeSAML2Test method testExchangeToSAML2UnsignedAndUnencryptedAssertion.

@Test
@UncaughtServerErrorExpected
public void testExchangeToSAML2UnsignedAndUnencryptedAssertion() 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_UNSIGNED_AND_UNENCRYPTED_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
        Document assertionDoc = DocumentUtil.getDocument(assertionXML);
        Assert.assertFalse(AssertionUtil.isSignedElement(assertionDoc.getDocumentElement()));
        AssertionType assertion = (AssertionType) SAMLParser.getInstance().parse(assertionDoc);
        // Audience
        AudienceRestrictionType aud = (AudienceRestrictionType) assertion.getConditions().getConditions().get(0);
        Assert.assertEquals(SAML_UNSIGNED_AND_UNENCRYPTED_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) 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 40 with AssertionType

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

the class SAMLDataMarshallerTest method testSerializeWithNamespaceNotInSignatureElement.

@Test
public void testSerializeWithNamespaceNotInSignatureElement() throws Exception {
    SAMLParser parser = SAMLParser.getInstance();
    try (InputStream st = SAMLDataMarshallerTest.class.getResourceAsStream("saml-response-ds-ns-above-signature.xml")) {
        Object parsedObject = parser.parse(st);
        assertThat(parsedObject, instanceOf(ResponseType.class));
        ResponseType response = (ResponseType) parsedObject;
        SAMLDataMarshaller serializer = new SAMLDataMarshaller();
        String serializedResponse = serializer.serialize(response);
        String serializedAssertion = serializer.serialize(response.getAssertions().get(0).getAssertion());
        ResponseType deserializedResponse = serializer.deserialize(serializedResponse, ResponseType.class);
        assertThat(deserializedResponse, CoreMatchers.notNullValue());
        assertThat(deserializedResponse.getID(), CoreMatchers.is("id-EYgqtumZ-P-Ph7t37f-brUKMwB5MKix0sNjr-0YV"));
        AssertionType deserializedAssertion = serializer.deserialize(serializedAssertion, AssertionType.class);
        assertThat(deserializedAssertion, CoreMatchers.notNullValue());
        assertThat(deserializedAssertion.getID(), CoreMatchers.is("id-4r-Xj702KQsM0gJyu3Fqpuwfe-LvDrEcQZpxKrhC"));
    }
}
Also used : InputStream(java.io.InputStream) SAMLParser(org.keycloak.saml.processing.core.parsers.saml.SAMLParser) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) SAMLDataMarshaller(org.keycloak.broker.saml.SAMLDataMarshaller) ResponseType(org.keycloak.dom.saml.v2.protocol.ResponseType) Test(org.junit.Test)

Aggregations

AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)43 Test (org.junit.Test)24 ResponseType (org.keycloak.dom.saml.v2.protocol.ResponseType)21 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)20 EncryptedAssertionType (org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType)15 AttributeStatementType (org.keycloak.dom.saml.v2.assertion.AttributeStatementType)13 AttributeType (org.keycloak.dom.saml.v2.assertion.AttributeType)13 Element (org.w3c.dom.Element)12 List (java.util.List)11 XMLGregorianCalendar (javax.xml.datatype.XMLGregorianCalendar)11 AuthnStatementType (org.keycloak.dom.saml.v2.assertion.AuthnStatementType)10 Document (org.w3c.dom.Document)10 AudienceRestrictionType (org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType)9 ConditionsType (org.keycloak.dom.saml.v2.assertion.ConditionsType)9 SubjectType (org.keycloak.dom.saml.v2.assertion.SubjectType)9 StatementAbstractType (org.keycloak.dom.saml.v2.assertion.StatementAbstractType)8 ProcessingException (org.keycloak.saml.common.exceptions.ProcessingException)8 HashMap (java.util.HashMap)7 StatusResponseType (org.keycloak.dom.saml.v2.protocol.StatusResponseType)7 SAML2Object (org.keycloak.dom.saml.v2.SAML2Object)6