Search in sources :

Example 1 with IDToken

use of org.keycloak.representations.IDToken in project vboard by voyages-sncf-technologies.

the class AuthenticationController method getUserEmailFromAuth.

private static String getUserEmailFromAuth(Authentication auth) {
    if (auth instanceof JsonWebTokenAuthentication) {
        return ((JsonWebTokenAuthentication) auth).getEmail();
    }
    final KeycloakPrincipal userDetails = (KeycloakPrincipal) auth.getPrincipal();
    final IDToken idToken = userDetails.getKeycloakSecurityContext().getToken();
    return idToken.getEmail();
}
Also used : JsonWebTokenAuthentication(com.vsct.vboard.config.cognito.JsonWebTokenAuthentication) IDToken(org.keycloak.representations.IDToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 2 with IDToken

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

the class AdapterTokenVerifier method verifyTokens.

/**
 * Verify access token and ID token. Typically called after successful tokenResponse is received from Keycloak
 *
 * @param accessTokenString
 * @param idTokenString
 * @param deployment
 * @return verified and parsed accessToken and idToken
 * @throws VerificationException
 */
public static VerifiedTokens verifyTokens(String accessTokenString, String idTokenString, KeycloakDeployment deployment) throws VerificationException {
    // Adapters currently do most of the checks including signature etc on the access token
    TokenVerifier<AccessToken> tokenVerifier = createVerifier(accessTokenString, deployment, true, AccessToken.class);
    AccessToken accessToken = tokenVerifier.verify().getToken();
    if (idTokenString != null) {
        // Don't verify signature again on IDToken
        IDToken idToken = TokenVerifier.create(idTokenString, IDToken.class).getToken();
        TokenVerifier<IDToken> idTokenVerifier = TokenVerifier.createWithoutSignature(idToken);
        // Always verify audience and azp on IDToken
        idTokenVerifier.audience(deployment.getResourceName());
        idTokenVerifier.issuedFor(deployment.getResourceName());
        idTokenVerifier.verify();
        return new VerifiedTokens(accessToken, idToken);
    } else {
        return new VerifiedTokens(accessToken, null);
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) IDToken(org.keycloak.representations.IDToken)

Example 3 with IDToken

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

the class KcOidcBrokerNonceParameterTest method loginUser.

@Override
protected void loginUser() {
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    oauth.realm(bc.consumerRealmName());
    oauth.clientId("consumer-client");
    oauth.nonce("123456");
    OAuthClient.AuthorizationEndpointResponse authzResponse = oauth.doLoginSocial(bc.getIDPAlias(), bc.getUserLogin(), bc.getUserPassword());
    String code = authzResponse.getCode();
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);
    IDToken idToken = toIdToken(response.getIdToken());
    Assert.assertEquals("123456", idToken.getNonce());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) IDToken(org.keycloak.representations.IDToken)

Example 4 with IDToken

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

the class LDAPMultipleAttributesTest method ldapPortalEndToEndTest.

@Test
public void ldapPortalEndToEndTest() {
    // Login as bwilson
    oauth.clientId("ldap-portal");
    oauth.redirectUri(suiteContext.getAuthServerInfo().getContextRoot().toString() + "/ldap-portal");
    loginPage.open();
    loginPage.login("bwilson", "Password1");
    String code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, "password");
    Assert.assertEquals(200, response.getStatusCode());
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());
    Assert.assertEquals("Bruce Wilson", idToken.getName());
    Assert.assertEquals("Elm 5", idToken.getOtherClaims().get("street"));
    Collection postalCodes = (Collection) idToken.getOtherClaims().get("postal_code");
    Assert.assertEquals(2, postalCodes.size());
    Assert.assertTrue(postalCodes.contains("88441"));
    Assert.assertTrue(postalCodes.contains("77332"));
    oauth.doLogout(response.getRefreshToken(), "password");
    // Login as jbrown
    loginPage.open();
    loginPage.login("jbrown", "Password1");
    code = new OAuthClient.AuthorizationEndpointResponse(oauth).getCode();
    response = oauth.doAccessTokenRequest(code, "password");
    org.keycloak.testsuite.Assert.assertEquals(200, response.getStatusCode());
    idToken = oauth.verifyIDToken(response.getIdToken());
    Assert.assertEquals("James Brown", idToken.getName());
    Assert.assertNull(idToken.getOtherClaims().get("street"));
    postalCodes = (Collection) idToken.getOtherClaims().get("postal_code");
    Assert.assertEquals(1, postalCodes.size());
    Assert.assertTrue(postalCodes.contains("88441"));
    Assert.assertFalse(postalCodes.contains("77332"));
    oauth.doLogout(response.getRefreshToken(), "password");
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) Collection(java.util.Collection) IDToken(org.keycloak.representations.IDToken) Test(org.junit.Test)

Example 5 with IDToken

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

the class OIDCAdvancedRequestParamsTest method processClaimsRequestParamSupported.

@Test
public void processClaimsRequestParamSupported() throws Exception {
    String clientScopeId = null;
    try {
        for (ClientScopeRepresentation rep : adminClient.realm("test").clientScopes().findAll()) {
            if (rep.getName().equals("profile")) {
                clientScopeId = rep.getId();
                break;
            }
        }
        findClientResourceByClientId(adminClient.realm("test"), "test-app").removeDefaultClientScope(clientScopeId);
        ClientResource app = findClientResourceByClientId(adminClient.realm("test"), "test-app");
        ProtocolMappersResource res = app.getProtocolMappers();
        res.createMapper(ModelToRepresentation.toRepresentation(ClaimsParameterTokenMapper.createMapper("claimsParameterTokenMapper", true, false))).close();
        Map<String, Object> claims = ImmutableMap.of("id_token", ImmutableMap.of("email", ImmutableMap.of("essential", true), "preferred_username", ImmutableMap.of("essential", true), "family_name", ImmutableMap.of("essential", false), "given_name", ImmutableMap.of("wesentlich", true), "name", ImmutableMap.of("essential", true)), "userinfo", ImmutableMap.of("preferred_username", ImmutableMap.of("essential", "Ja"), "family_name", ImmutableMap.of("essential", true), "given_name", ImmutableMap.of("essential", true)));
        Map<String, Object> oidcRequest = new HashMap<>();
        oidcRequest.put(OIDCLoginProtocol.CLIENT_ID_PARAM, "test-app");
        oidcRequest.put(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
        oidcRequest.put(OIDCLoginProtocol.REDIRECT_URI_PARAM, oauth.getRedirectUri());
        oidcRequest.put(OIDCLoginProtocol.CLAIMS_PARAM, claims);
        oidcRequest.put(OIDCLoginProtocol.SCOPE_PARAM, "openid");
        String request = new JWSBuilder().jsonContent(oidcRequest).none();
        oauth = oauth.request(request);
        oauth.doLogin("test-user@localhost", "password");
        EventRepresentation loginEvent = events.expectLogin().assertEvent();
        OAuthClient.AccessTokenResponse accessTokenResponse = sendTokenRequestAndGetResponse(loginEvent);
        IDToken idToken = oauth.verifyIDToken(accessTokenResponse.getIdToken());
        assertEquals("test-user@localhost", idToken.getEmail());
        assertEquals("test-user@localhost", idToken.getPreferredUsername());
        assertNull(idToken.getFamilyName());
        assertNull(idToken.getGivenName());
        assertEquals("Tom Brady", idToken.getName());
        Client client = AdminClientUtil.createResteasyClient();
        try {
            Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getAccessToken());
            UserInfo userInfo = response.readEntity(UserInfo.class);
            assertEquals("test-user@localhost", userInfo.getEmail());
            assertNull(userInfo.getPreferredUsername());
            assertEquals("Brady", userInfo.getFamilyName());
            assertEquals("Tom", userInfo.getGivenName());
            assertNull(userInfo.getName());
        } finally {
            events.expect(EventType.USER_INFO_REQUEST).session(accessTokenResponse.getSessionState()).client("test-app").assertEvent();
            client.close();
        }
        oauth.doLogout(accessTokenResponse.getRefreshToken(), "password");
        events.expectLogout(accessTokenResponse.getSessionState()).client("test-app").clearDetails().assertEvent();
        claims = ImmutableMap.of("id_token", ImmutableMap.of("test_claim", ImmutableMap.of("essential", true)), "access_token", ImmutableMap.of("email", ImmutableMap.of("essential", true), "preferred_username", ImmutableMap.of("essential", true), "family_name", ImmutableMap.of("essential", true), "given_name", ImmutableMap.of("essential", true), "name", ImmutableMap.of("essential", true)));
        oidcRequest = new HashMap<>();
        oidcRequest.put(OIDCLoginProtocol.CLIENT_ID_PARAM, "test-app");
        oidcRequest.put(OIDCLoginProtocol.RESPONSE_TYPE_PARAM, OAuth2Constants.CODE);
        oidcRequest.put(OIDCLoginProtocol.REDIRECT_URI_PARAM, oauth.getRedirectUri());
        oidcRequest.put(OIDCLoginProtocol.CLAIMS_PARAM, claims);
        oidcRequest.put(OIDCLoginProtocol.SCOPE_PARAM, "openid");
        request = new JWSBuilder().jsonContent(oidcRequest).none();
        oauth = oauth.request(request);
        oauth.doLogin("test-user@localhost", "password");
        loginEvent = events.expectLogin().assertEvent();
        accessTokenResponse = sendTokenRequestAndGetResponse(loginEvent);
        idToken = oauth.verifyIDToken(accessTokenResponse.getIdToken());
        // "email" default scope still remains
        assertEquals("test-user@localhost", idToken.getEmail());
        assertNull(idToken.getPreferredUsername());
        assertNull(idToken.getFamilyName());
        assertNull(idToken.getGivenName());
        assertNull(idToken.getName());
        client = AdminClientUtil.createResteasyClient();
        try {
            Response response = UserInfoClientUtil.executeUserInfoRequest_getMethod(client, accessTokenResponse.getAccessToken());
            UserInfo userInfo = response.readEntity(UserInfo.class);
            assertEquals("test-user@localhost", userInfo.getEmail());
            assertNull(userInfo.getPreferredUsername());
            assertNull(userInfo.getFamilyName());
            assertNull(userInfo.getGivenName());
            assertNull(userInfo.getName());
        } finally {
            client.close();
        }
    } finally {
        // revert "profile" default client scope
        findClientResourceByClientId(adminClient.realm("test"), "test-app").addDefaultClientScope(clientScopeId);
    }
}
Also used : HashMap(java.util.HashMap) MultivaluedHashMap(org.keycloak.common.util.MultivaluedHashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) UserInfo(org.keycloak.representations.UserInfo) JWSBuilder(org.keycloak.jose.jws.JWSBuilder) Response(javax.ws.rs.core.Response) ClientScopeRepresentation(org.keycloak.representations.idm.ClientScopeRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) IDToken(org.keycloak.representations.IDToken) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) ProtocolMappersResource(org.keycloak.admin.client.resource.ProtocolMappersResource) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Aggregations

IDToken (org.keycloak.representations.IDToken)89 Test (org.junit.Test)57 OAuthClient (org.keycloak.testsuite.util.OAuthClient)53 AbstractKeycloakTest (org.keycloak.testsuite.AbstractKeycloakTest)25 EventRepresentation (org.keycloak.representations.idm.EventRepresentation)23 ProtocolMappersResource (org.keycloak.admin.client.resource.ProtocolMappersResource)18 AccessToken (org.keycloak.representations.AccessToken)18 HashMap (java.util.HashMap)16 ClientRepresentation (org.keycloak.representations.idm.ClientRepresentation)16 ClientResource (org.keycloak.admin.client.resource.ClientResource)15 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)14 Matchers.isEmptyOrNullString (org.hamcrest.Matchers.isEmptyOrNullString)13 ProtocolMapperRepresentation (org.keycloak.representations.idm.ProtocolMapperRepresentation)12 List (java.util.List)11 Map (java.util.Map)11 UserResource (org.keycloak.admin.client.resource.UserResource)11 GroupRepresentation (org.keycloak.representations.idm.GroupRepresentation)10 OIDCClientRepresentation (org.keycloak.representations.oidc.OIDCClientRepresentation)10 AbstractAdminTest (org.keycloak.testsuite.admin.AbstractAdminTest)9 RefreshToken (org.keycloak.representations.RefreshToken)5