Search in sources :

Example 31 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class ServiceAccountTest method clientCredentialsAuthSuccessWithoutRefreshTokenImpl.

// Returns accessToken string
private String clientCredentialsAuthSuccessWithoutRefreshTokenImpl() throws Exception {
    oauth.clientId("service-account-cl");
    OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1");
    assertEquals(200, response.getStatusCode());
    String tokenString = response.getAccessToken();
    Assert.assertNotNull("Access-Token should be present", tokenString);
    AccessToken accessToken = oauth.verifyToken(tokenString);
    Assert.assertNull(accessToken.getSessionState());
    Assert.assertNull("Refresh-Token should not be present", response.getRefreshToken());
    events.expectClientLogin().client("service-account-cl").user(AssertEvents.isUUID()).session(AssertEvents.isUUID()).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "service-account-cl").assertEvent();
    // new clients which use client-credentials grant should NOT create a refresh-token or session, see KEYCLOAK-9551.
    List<Map<String, String>> clientSessionStats = getAdminClient().realm(oauth.getRealm()).getClientSessionStats();
    assertThat(clientSessionStats, empty());
    // Check that token is possible to introspect
    Assert.assertTrue(getIntrospectionResponse("service-account-cl", "secret1", tokenString));
    events.expect(EventType.INTROSPECT_TOKEN).client("service-account-cl").user(AssertEvents.isUUID()).user(Matchers.isEmptyOrNullString()).session(Matchers.isEmptyOrNullString()).assertEvent();
    return tokenString;
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) Map(java.util.Map)

Example 32 with AccessToken

use of org.keycloak.representations.AccessToken in project keycloak by keycloak.

the class ServiceAccountTest method changeClientIdTest.

@Test
public void changeClientIdTest() throws Exception {
    ClientManager.realm(adminClient.realm("test")).clientId("service-account-cl-refresh-on").renameTo("updated-client");
    oauth.clientId("updated-client");
    OAuthClient.AccessTokenResponse response = oauth.doClientCredentialsGrantAccessTokenRequest("secret1");
    assertEquals(200, response.getStatusCode());
    AccessToken accessToken = oauth.verifyToken(response.getAccessToken());
    Assert.assertEquals("updated-client", accessToken.getOtherClaims().get(ServiceAccountConstants.CLIENT_ID));
    // Username updated after client ID changed
    events.expectClientLogin().client("updated-client").user(userId).session(accessToken.getSessionState()).detail(Details.TOKEN_ID, accessToken.getId()).detail(Details.USERNAME, ServiceAccountConstants.SERVICE_ACCOUNT_USER_PREFIX + "updated-client").assertEvent();
    ClientManager.realm(adminClient.realm("test")).clientId("updated-client").renameTo("service-account-cl-refresh-on");
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) AccessToken(org.keycloak.representations.AccessToken) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 33 with AccessToken

use of org.keycloak.representations.AccessToken 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 34 with AccessToken

use of org.keycloak.representations.AccessToken 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 35 with AccessToken

use of org.keycloak.representations.AccessToken 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

AccessToken (org.keycloak.representations.AccessToken)230 Test (org.junit.Test)129 OAuthClient (org.keycloak.testsuite.util.OAuthClient)104 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)54 RefreshToken (org.keycloak.representations.RefreshToken)45 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)37 JWSInput (org.keycloak.jose.jws.JWSInput)29 Permission (org.keycloak.representations.idm.authorization.Permission)28 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)27 Response (javax.ws.rs.core.Response)26 ClientResource (org.keycloak.admin.client.resource.ClientResource)22 VerificationException (org.keycloak.common.VerificationException)19 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)19 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)18 IDToken (org.keycloak.representations.IDToken)18 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)17 IOException (java.io.IOException)15 AuthzClient (org.keycloak.authorization.client.AuthzClient)15 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)14 ArrayList (java.util.ArrayList)13