Search in sources :

Example 51 with IDToken

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

the class KcOidcBrokerNonceParameterTest method testNonceNotSet.

@Test
public void testNonceNotSet() {
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    oauth.realm(bc.consumerRealmName());
    oauth.clientId("consumer-client");
    oauth.nonce(null);
    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.assertNull(idToken.getNonce());
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) IDToken(org.keycloak.representations.IDToken) Test(org.junit.Test)

Example 52 with IDToken

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

the class CIBATest method testBackchannelAuthenticationFlow.

private void testBackchannelAuthenticationFlow(boolean isOfflineAccess, String bindingMessage) throws Exception {
    ClientResource clientResource = null;
    ClientRepresentation clientRep = null;
    try {
        final String username = "nutzername-rot";
        Map<String, String> additionalParameters = new HashMap<>();
        additionalParameters.put("user_device", "mobile");
        // prepare CIBA settings
        clientResource = ApiUtil.findClientByClientId(adminClient.realm(TEST_REALM_NAME), TEST_CLIENT_NAME);
        assertThat(clientResource, notNullValue());
        clientRep = clientResource.toRepresentation();
        prepareCIBASettings(clientResource, clientRep);
        if (isOfflineAccess)
            oauth.scope(OAuth2Constants.OFFLINE_ACCESS);
        long startTime = Time.currentTime();
        // user Backchannel Authentication Request
        AuthenticationRequestAcknowledgement response = doBackchannelAuthenticationRequest(TEST_CLIENT_NAME, TEST_CLIENT_PASSWORD, username, bindingMessage, null, additionalParameters);
        // user Authentication Channel Request
        TestAuthenticationChannelRequest testRequest = doAuthenticationChannelRequest(bindingMessage);
        AuthenticationChannelRequest authenticationChannelReq = testRequest.getRequest();
        assertThat(authenticationChannelReq.getBindingMessage(), is(equalTo(bindingMessage)));
        if (isOfflineAccess)
            assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.OFFLINE_ACCESS)));
        assertThat(authenticationChannelReq.getScope(), is(containsString(OAuth2Constants.SCOPE_OPENID)));
        assertThat(authenticationChannelReq.getAdditionalParameters().get("user_device"), is(equalTo("mobile")));
        // user Authentication Channel completed
        EventRepresentation loginEvent = doAuthenticationChannelCallback(testRequest);
        String sessionId = loginEvent.getSessionId();
        String codeId = loginEvent.getDetails().get(Details.CODE_ID);
        String userId = loginEvent.getUserId();
        // user Token Request
        OAuthClient.AccessTokenResponse tokenRes = doBackchannelAuthenticationTokenRequest(username, response.getAuthReqId());
        IDToken idToken = oauth.verifyIDToken(tokenRes.getIdToken());
        long currentTime = Time.currentTime();
        long authTime = idToken.getAuth_time().longValue();
        assertTrue(startTime - 5 <= authTime);
        assertTrue(authTime <= currentTime + 5);
        // token introspection
        String tokenResponse = doIntrospectAccessTokenWithClientCredential(tokenRes, username);
        // token refresh
        tokenRes = doRefreshTokenRequest(tokenRes.getRefreshToken(), username, sessionId, isOfflineAccess);
        // token introspection after token refresh
        tokenResponse = doIntrospectAccessTokenWithClientCredential(tokenRes, username);
        // logout by refresh token
        EventRepresentation logoutEvent = doLogoutByRefreshToken(tokenRes.getRefreshToken(), sessionId, userId, isOfflineAccess);
    } finally {
        revertCIBASettings(clientResource, clientRep);
    }
}
Also used : HashMap(java.util.HashMap) OAuthClient(org.keycloak.testsuite.util.OAuthClient) EventRepresentation(org.keycloak.representations.idm.EventRepresentation) Matchers.containsString(org.hamcrest.Matchers.containsString) AuthenticationRequestAcknowledgement(org.keycloak.testsuite.util.OAuthClient.AuthenticationRequestAcknowledgement) OIDCClientRepresentation(org.keycloak.representations.oidc.OIDCClientRepresentation) ClientRepresentation(org.keycloak.representations.idm.ClientRepresentation) ClientResource(org.keycloak.admin.client.resource.ClientResource) AuthenticationChannelRequest(org.keycloak.protocol.oidc.grants.ciba.channel.AuthenticationChannelRequest) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest) IDToken(org.keycloak.representations.IDToken) TestAuthenticationChannelRequest(org.keycloak.testsuite.rest.representation.TestAuthenticationChannelRequest)

Example 53 with IDToken

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

the class FAPI1Test method assertSuccessfulTokenResponse.

private void assertSuccessfulTokenResponse(OAuthClient.AccessTokenResponse tokenResponse) {
    assertEquals(200, tokenResponse.getStatusCode());
    Assert.assertThat(tokenResponse.getIdToken(), Matchers.notNullValue());
    Assert.assertThat(tokenResponse.getAccessToken(), Matchers.notNullValue());
    // Scope parameter must be present per FAPI
    Assert.assertNotNull(tokenResponse.getScope());
    assertScopes("openid profile email", tokenResponse.getScope());
    // ID Token contains all the claims
    IDToken idToken = oauth.verifyIDToken(tokenResponse.getIdToken());
    Assert.assertNotNull(idToken.getId());
    Assert.assertEquals("foo", idToken.getIssuedFor());
    Assert.assertEquals("john", idToken.getPreferredUsername());
    Assert.assertEquals("john@keycloak.org", idToken.getEmail());
    Assert.assertEquals("Johny", idToken.getGivenName());
    Assert.assertEquals(idToken.getNonce(), "123456");
}
Also used : IDToken(org.keycloak.representations.IDToken)

Example 54 with IDToken

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

the class ScriptBasedOIDCProtocolMapper method evaluateScript.

private Object evaluateScript(Object tokenBinding, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession) {
    UserModel user = userSession.getUser();
    String scriptSource = getScriptCode(mappingModel);
    RealmModel realm = userSession.getRealm();
    ScriptingProvider scripting = keycloakSession.getProvider(ScriptingProvider.class);
    ScriptModel scriptModel = scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, "token-mapper-script_" + mappingModel.getName(), scriptSource, null);
    EvaluatableScriptAdapter script = scripting.prepareEvaluatableScript(scriptModel);
    Object claimValue;
    try {
        claimValue = script.eval((bindings) -> {
            bindings.put("user", user);
            bindings.put("realm", realm);
            if (tokenBinding instanceof IDToken) {
                bindings.put("token", tokenBinding);
            } else if (tokenBinding instanceof AccessTokenResponse) {
                bindings.put("tokenResponse", tokenBinding);
            }
            bindings.put("userSession", userSession);
            bindings.put("keycloakSession", keycloakSession);
        });
    } catch (Exception ex) {
        LOGGER.error("Error during execution of ProtocolMapper script", ex);
        claimValue = null;
    }
    return claimValue;
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) ScriptModel(org.keycloak.models.ScriptModel) ProtocolMapperContainerModel(org.keycloak.models.ProtocolMapperContainerModel) RealmModel(org.keycloak.models.RealmModel) Profile(org.keycloak.common.Profile) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) ProtocolMapperConfigException(org.keycloak.protocol.ProtocolMapperConfigException) Logger(org.jboss.logging.Logger) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) KeycloakSession(org.keycloak.models.KeycloakSession) UserSessionModel(org.keycloak.models.UserSessionModel) EnvironmentDependentProviderFactory(org.keycloak.provider.EnvironmentDependentProviderFactory) IDToken(org.keycloak.representations.IDToken) ProviderConfigurationBuilder(org.keycloak.provider.ProviderConfigurationBuilder) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ScriptModel(org.keycloak.models.ScriptModel) EvaluatableScriptAdapter(org.keycloak.scripting.EvaluatableScriptAdapter) List(java.util.List) UserModel(org.keycloak.models.UserModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) ScriptingProvider(org.keycloak.scripting.ScriptingProvider) ScriptCompilationException(org.keycloak.scripting.ScriptCompilationException) ProtocolMapperUtils(org.keycloak.protocol.ProtocolMapperUtils) ScriptingProvider(org.keycloak.scripting.ScriptingProvider) EvaluatableScriptAdapter(org.keycloak.scripting.EvaluatableScriptAdapter) IDToken(org.keycloak.representations.IDToken) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse) ProtocolMapperConfigException(org.keycloak.protocol.ProtocolMapperConfigException) ScriptCompilationException(org.keycloak.scripting.ScriptCompilationException)

Example 55 with IDToken

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

the class FullNameMapper method setClaim.

protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    List<String> parts = new LinkedList<>();
    Optional.ofNullable(user.getFirstName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    Optional.ofNullable(user.getLastName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    if (!parts.isEmpty()) {
        token.getOtherClaims().put("name", String.join(" ", parts));
    }
}
Also used : UserModel(org.keycloak.models.UserModel) List(java.util.List) UserModel(org.keycloak.models.UserModel) ProtocolMapperModel(org.keycloak.models.ProtocolMapperModel) Map(java.util.Map) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) HashMap(java.util.HashMap) UserSessionModel(org.keycloak.models.UserSessionModel) LinkedList(java.util.LinkedList) IDToken(org.keycloak.representations.IDToken) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList)

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