Search in sources :

Example 1 with UncaughtServerErrorExpected

use of org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testAccountLinkNoTokenStore.

@Test
@UncaughtServerErrorExpected
public void testAccountLinkNoTokenStore() throws Exception {
    testingClient.server().run(BrokerLinkAndTokenExchangeTest::turnOffTokenStore);
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    UriBuilder linkBuilder = UriBuilder.fromUri(appPage.getInjectedUrl().toString()).path("link");
    String linkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    System.out.println("After linking: " + driver.getCurrentUrl());
    System.out.println(driver.getPageSource());
    Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    Assert.assertTrue(driver.getPageSource().contains("Exchange token received"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    logoutAll();
    realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
}
Also used : RealmResource(org.keycloak.admin.client.resource.RealmResource) UriBuilder(javax.ws.rs.core.UriBuilder) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 2 with UncaughtServerErrorExpected

use of org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected in project keycloak by keycloak.

the class BrokerLinkAndTokenExchangeTest method testAccountLink.

@Test
@UncaughtServerErrorExpected
public void testAccountLink() throws Exception {
    testingClient.server().run(BrokerLinkAndTokenExchangeTest::turnOnTokenStore);
    RealmResource realm = adminClient.realms().realm(CHILD_IDP);
    List<FederatedIdentityRepresentation> links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertTrue(links.isEmpty());
    String servletUri = appPage.getInjectedUrl().toString();
    UriBuilder linkBuilder = UriBuilder.fromUri(servletUri).path("link");
    String linkUrl = linkBuilder.clone().queryParam("realm", CHILD_IDP).queryParam("provider", PARENT_IDP).build().toString();
    System.out.println("linkUrl: " + linkUrl);
    navigateTo(linkUrl);
    Assert.assertTrue(loginPage.isCurrent(CHILD_IDP));
    Assert.assertTrue(driver.getPageSource().contains(PARENT_IDP));
    loginPage.login("child", "password");
    Assert.assertTrue(loginPage.isCurrent(PARENT_IDP));
    loginPage.login(PARENT_USERNAME, "password");
    System.out.println("After linking: " + driver.getCurrentUrl());
    System.out.println(driver.getPageSource());
    Assert.assertTrue(driver.getCurrentUrl().startsWith(linkBuilder.toTemplate()));
    Assert.assertTrue(driver.getPageSource().contains("Account Linked"));
    Assert.assertTrue(driver.getPageSource().contains("Exchange token received"));
    links = realm.users().get(childUserId).getFederatedIdentity();
    Assert.assertFalse(links.isEmpty());
    // do exchange
    String accessToken = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, ClientApp.DEPLOYMENT_NAME, "password").getAccessToken();
    Client httpClient = AdminClientUtil.createResteasyClient();
    try {
        WebTarget exchangeUrl = childTokenExchangeWebTarget(httpClient);
        System.out.println("Exchange url: " + exchangeUrl.getUri().toString());
        Response response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        AccessTokenResponse tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        String externalToken = tokenResponse.getToken();
        Assert.assertNotNull(externalToken);
        Assert.assertTrue(tokenResponse.getExpiresIn() > 0);
        setTimeOffset((int) tokenResponse.getExpiresIn() + 1);
        // test that token refresh happens
        // get access token again because we may have timed out
        accessToken = oauth.doGrantAccessTokenRequest(CHILD_IDP, "child", "password", null, ClientApp.DEPLOYMENT_NAME, "password").getAccessToken();
        response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader(ClientApp.DEPLOYMENT_NAME, "password")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.SUBJECT_TOKEN, accessToken).param(OAuth2Constants.SUBJECT_TOKEN_TYPE, OAuth2Constants.ACCESS_TOKEN_TYPE).param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        Assert.assertNotEquals(externalToken, tokenResponse.getToken());
        // test direct exchange
        response = exchangeUrl.request().header(HttpHeaders.AUTHORIZATION, BasicAuthHelper.createHeader("direct-exchanger", "secret")).post(Entity.form(new Form().param(OAuth2Constants.GRANT_TYPE, OAuth2Constants.TOKEN_EXCHANGE_GRANT_TYPE).param(OAuth2Constants.REQUESTED_SUBJECT, "child").param(OAuth2Constants.REQUESTED_ISSUER, PARENT_IDP)));
        Assert.assertEquals(200, response.getStatus());
        tokenResponse = response.readEntity(AccessTokenResponse.class);
        response.close();
        Assert.assertNotEquals(externalToken, tokenResponse.getToken());
        logoutAll();
        realm.users().get(childUserId).removeFederatedIdentity(PARENT_IDP);
        links = realm.users().get(childUserId).getFederatedIdentity();
        Assert.assertTrue(links.isEmpty());
    } finally {
        httpClient.close();
    }
}
Also used : AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Response(javax.ws.rs.core.Response) Form(javax.ws.rs.core.Form) RealmResource(org.keycloak.admin.client.resource.RealmResource) WebTarget(javax.ws.rs.client.WebTarget) UriBuilder(javax.ws.rs.core.UriBuilder) OAuthClient(org.keycloak.testsuite.util.OAuthClient) ApiUtil.createUserAndResetPasswordWithAdminClient(org.keycloak.testsuite.admin.ApiUtil.createUserAndResetPasswordWithAdminClient) Client(javax.ws.rs.client.Client) FederatedIdentityRepresentation(org.keycloak.representations.idm.FederatedIdentityRepresentation) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) Test(org.junit.Test) AbstractServletsAdapterTest(org.keycloak.testsuite.adapter.AbstractServletsAdapterTest) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Example 3 with UncaughtServerErrorExpected

use of org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected 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 4 with UncaughtServerErrorExpected

use of org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected 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 5 with UncaughtServerErrorExpected

use of org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected in project keycloak by keycloak.

the class ClientTokenExchangeSAML2Test method testBadImpersonator.

@Test
@UncaughtServerErrorExpected
public void testBadImpersonator() throws Exception {
    testingClient.server().run(ClientTokenExchangeSAML2Test::setupRealm);
    oauth.realm(TEST);
    oauth.clientId("client-exchanger");
    OAuthClient.AccessTokenResponse response = oauth.doGrantAccessTokenRequest("secret", "bad-impersonator", "password");
    String accessToken = response.getAccessToken();
    TokenVerifier<AccessToken> accessTokenVerifier = TokenVerifier.create(accessToken, AccessToken.class);
    AccessToken token = accessTokenVerifier.parse().getToken();
    Assert.assertEquals(token.getPreferredUsername(), "bad-impersonator");
    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);
    // test that user does not have impersonator permission
    {
        params.put(OAuth2Constants.REQUESTED_SUBJECT, "impersonated-user");
        response = oauth.doTokenExchange(TEST, accessToken, SAML_SIGNED_TARGET, "client-exchanger", "secret", params);
        Assert.assertEquals(403, response.getStatusCode());
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) HashMap(java.util.HashMap) AccessToken(org.keycloak.representations.AccessToken) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test) UncaughtServerErrorExpected(org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)

Aggregations

Test (org.junit.Test)27 UncaughtServerErrorExpected (org.keycloak.testsuite.arquillian.annotation.UncaughtServerErrorExpected)27 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)17 OAuthClient (org.keycloak.testsuite.util.OAuthClient)16 AccessToken (org.keycloak.representations.AccessToken)11 Response (javax.ws.rs.core.Response)10 HashMap (java.util.HashMap)7 List (java.util.List)7 Client (javax.ws.rs.client.Client)6 WebTarget (javax.ws.rs.client.WebTarget)6 Form (javax.ws.rs.core.Form)6 AssertionType (org.keycloak.dom.saml.v2.assertion.AssertionType)6 AudienceRestrictionType (org.keycloak.dom.saml.v2.assertion.AudienceRestrictionType)6 NameIDType (org.keycloak.dom.saml.v2.assertion.NameIDType)6 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)6 Element (org.w3c.dom.Element)5 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)4 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 TokenVerifier (org.keycloak.TokenVerifier)3 ClientResource (org.keycloak.admin.client.resource.ClientResource)3