Search in sources :

Example 66 with IDToken

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

the class OIDCAdvancedRequestParamsTest method nonSupportedParams.

// DISPLAY & OTHERS
@Test
public void nonSupportedParams() {
    driver.navigate().to(oauth.getLoginFormUrl() + "&display=popup&foo=foobar&claims_locales=fr");
    loginPage.assertCurrent();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    IDToken idToken = sendTokenRequestAndGetIDToken(loginEvent);
    Assert.assertNotNull(idToken);
}
Also used : EventRepresentation(org.keycloak.representations.idm.EventRepresentation) IDToken(org.keycloak.representations.IDToken) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 67 with IDToken

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

the class OIDCAdvancedRequestParamsTest method promptLogin.

// prompt=login
@Test
public void promptLogin() {
    // Login user
    loginPage.open();
    loginPage.login("test-user@localhost", "password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    EventRepresentation loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    IDToken oldIdToken = sendTokenRequestAndGetIDToken(loginEvent);
    // Set time offset
    setTimeOffset(10);
    // SSO login first WITHOUT prompt=login ( Tests KEYCLOAK-5248 )
    driver.navigate().to(oauth.getLoginFormUrl());
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    IDToken newIdToken = sendTokenRequestAndGetIDToken(loginEvent);
    // Assert that authTime wasn't updated
    Assert.assertEquals(oldIdToken.getAuthTime(), newIdToken.getAuthTime());
    // Set time offset
    setTimeOffset(20);
    // Assert need to re-authenticate with prompt=login
    driver.navigate().to(oauth.getLoginFormUrl() + "&prompt=login");
    loginPage.assertCurrent();
    Assert.assertThat(false, is(loginPage.isUsernameInputPresent()));
    loginPage.login("password");
    Assert.assertEquals(AppPage.RequestType.AUTH_RESPONSE, appPage.getRequestType());
    loginEvent = events.expectLogin().detail(Details.USERNAME, "test-user@localhost").assertEvent();
    newIdToken = sendTokenRequestAndGetIDToken(loginEvent);
    // Assert that authTime was updated
    Assert.assertTrue("Expected auth time to change. old auth time: " + oldIdToken.getAuthTime() + " , new auth time: " + newIdToken.getAuthTime(), oldIdToken.getAuthTime() + 20 <= newIdToken.getAuthTime());
    // Assert userSession didn't change
    Assert.assertEquals(oldIdToken.getSessionState(), newIdToken.getSessionState());
}
Also used : EventRepresentation(org.keycloak.representations.idm.EventRepresentation) IDToken(org.keycloak.representations.IDToken) AbstractAdminTest(org.keycloak.testsuite.admin.AbstractAdminTest) Test(org.junit.Test) AbstractTestRealmKeycloakTest(org.keycloak.testsuite.AbstractTestRealmKeycloakTest)

Example 68 with IDToken

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

the class RefreshTokenTest method tokenRefreshWithAccessTokenShouldReturnIdTokenWithAccessTokenHash.

/**
 * KEYCLOAK-15437
 */
@Test
public void tokenRefreshWithAccessTokenShouldReturnIdTokenWithAccessTokenHash() {
    oauth.doLogin("test-user@localhost", "password");
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse tokenResponse = oauth.doAccessTokenRequest(code, "password");
    String refreshToken = tokenResponse.getRefreshToken();
    setTimeOffset(2);
    try {
        OAuthClient.AccessTokenResponse response = oauth.doRefreshTokenRequest(refreshToken, "password");
        Assert.assertEquals(200, response.getStatusCode());
        IDToken idToken = oauth.verifyToken(response.getIdToken());
        Assert.assertNotNull("AccessTokenHash should not be null after token refresh", idToken.getAccessTokenHash());
    } finally {
        setTimeOffset(0);
    }
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) IDToken(org.keycloak.representations.IDToken) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 69 with IDToken

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

the class LogoutEndpoint method logout.

/**
 * Logout user session.  User must be logged in via a session cookie.
 *
 * When the logout is initiated by a remote idp, the parameter "initiating_idp" can be supplied. This param will
 * prevent upstream logout (since the logout procedure has already been started in the remote idp).
 *
 * @param redirectUri
 * @param initiatingIdp The alias of the idp initiating the logout.
 * @return
 */
@GET
@NoCache
public // deprecated
Response logout(// deprecated
@QueryParam(OIDCLoginProtocol.REDIRECT_URI_PARAM) String redirectUri, @QueryParam("id_token_hint") String encodedIdToken, @QueryParam("post_logout_redirect_uri") String postLogoutRedirectUri, @QueryParam("state") String state, @QueryParam("initiating_idp") String initiatingIdp) {
    String redirect = postLogoutRedirectUri != null ? postLogoutRedirectUri : redirectUri;
    IDToken idToken = null;
    if (encodedIdToken != null) {
        try {
            idToken = tokenManager.verifyIDTokenSignature(session, encodedIdToken);
            TokenVerifier.createWithoutSignature(idToken).tokenType(TokenUtil.TOKEN_TYPE_ID).verify();
        } catch (OAuthErrorException | VerificationException e) {
            event.event(EventType.LOGOUT);
            event.error(Errors.INVALID_TOKEN);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
        }
    }
    if (redirect != null) {
        String validatedUri;
        ClientModel client = (idToken == null || idToken.getIssuedFor() == null) ? null : realm.getClientByClientId(idToken.getIssuedFor());
        if (client != null) {
            validatedUri = RedirectUtils.verifyRedirectUri(session, redirect, client);
        } else {
            validatedUri = RedirectUtils.verifyRealmRedirectUri(session, redirect);
        }
        if (validatedUri == null) {
            event.event(EventType.LOGOUT);
            event.detail(Details.REDIRECT_URI, redirect);
            event.error(Errors.INVALID_REDIRECT_URI);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REDIRECT_URI);
        }
        redirect = validatedUri;
    }
    UserSessionModel userSession = null;
    if (idToken != null) {
        try {
            userSession = session.sessions().getUserSession(realm, idToken.getSessionState());
            if (userSession != null) {
                checkTokenIssuedAt(idToken, userSession);
            }
        } catch (OAuthErrorException e) {
            event.event(EventType.LOGOUT);
            event.error(Errors.INVALID_TOKEN);
            return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.SESSION_NOT_ACTIVE);
        }
    }
    // authenticate identity cookie, but ignore an access token timeout as we're logging out anyways.
    AuthenticationManager.AuthResult authResult = AuthenticationManager.authenticateIdentityCookie(session, realm, false);
    if (authResult != null) {
        userSession = userSession != null ? userSession : authResult.getSession();
        return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
    } else if (userSession != null) {
        // identity cookie is missing but there's valid id_token_hint which matches session cookie => continue with browser logout
        if (idToken != null && idToken.getSessionState().equals(AuthenticationManager.getSessionIdFromSessionCookie(session))) {
            return initiateBrowserLogout(userSession, redirect, state, initiatingIdp);
        }
        // this might happen when a backChannelLogout is already initiated from AuthenticationManager.authenticateIdentityCookie
        if (userSession.getState() != LOGGING_OUT && userSession.getState() != LOGGED_OUT) {
            // non browser logout
            event.event(EventType.LOGOUT);
            AuthenticationManager.backchannelLogout(session, realm, userSession, session.getContext().getUri(), clientConnection, headers, true);
            event.user(userSession.getUser()).session(userSession).success();
        }
    }
    if (redirect != null) {
        UriBuilder uriBuilder = UriBuilder.fromUri(redirect);
        if (state != null)
            uriBuilder.queryParam(OIDCLoginProtocol.STATE_PARAM, state);
        return Response.status(302).location(uriBuilder.build()).build();
    } else {
        // TODO Empty content with ok makes no sense. Should it display a page? Or use noContent?
        session.getProvider(SecurityHeadersProvider.class).options().allowEmptyContentType();
        return Response.ok().build();
    }
}
Also used : AuthenticationManager(org.keycloak.services.managers.AuthenticationManager) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) OAuthErrorException(org.keycloak.OAuthErrorException) VerificationException(org.keycloak.common.VerificationException) IDToken(org.keycloak.representations.IDToken) UriBuilder(javax.ws.rs.core.UriBuilder) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 70 with IDToken

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

the class OIDCProtocolMappersTest method testUserGroupRoleToAttributeMappers.

@Test
@AuthServerContainerExclude(AuthServer.REMOTE)
public void testUserGroupRoleToAttributeMappers() throws Exception {
    // Add mapper for realm roles
    String clientId = "test-app";
    ProtocolMapperRepresentation realmMapper = ProtocolMapperUtil.createUserRealmRoleMappingMapper("pref.", "Realm roles mapper", "roles-custom.realm", true, true);
    ProtocolMapperRepresentation clientMapper = ProtocolMapperUtil.createUserClientRoleMappingMapper(clientId, "ta.", "Client roles mapper", "roles-custom.test-app", true, true);
    ProtocolMappersResource protocolMappers = ApiUtil.findClientResourceByClientId(adminClient.realm("test"), clientId).getProtocolMappers();
    protocolMappers.createMapper(Arrays.asList(realmMapper, clientMapper));
    // Login user
    OAuthClient.AccessTokenResponse response = browserLogin("password", "rich.roles@redhat.com", "password");
    IDToken idToken = oauth.verifyIDToken(response.getIdToken());
    // Verify attribute is filled
    Map<String, Object> roleMappings = (Map<String, Object>) idToken.getOtherClaims().get("roles-custom");
    Assert.assertThat(roleMappings.keySet(), containsInAnyOrder("realm", clientId));
    String realmRoleMappings = (String) roleMappings.get("realm");
    String testAppMappings = (String) roleMappings.get(clientId);
    assertRolesString(realmRoleMappings, // from direct assignment to /roleRichGroup/level2group
    "pref.admin", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
    "pref.user", // from client role customer-admin-composite-role - realm role for test-app
    "pref.customer-user-premium", // from parent group of /roleRichGroup/level2group, i.e. from /roleRichGroup
    "pref.realm-composite-role", // from realm role realm-composite-role
    "pref.sample-realm-role");
    assertRolesString(testAppMappings, // from direct assignment to /roleRichGroup/level2group
    "ta.customer-user", // from direct assignment to /roleRichGroup/level2group
    "ta.customer-admin-composite-role", // from client role customer-admin-composite-role - client role for test-app
    "ta.customer-admin", // from realm role realm-composite-role - client role for test-app
    "ta.sample-client-role");
    // Revert
    deleteMappers(protocolMappers);
}
Also used : OAuthClient(org.keycloak.testsuite.util.OAuthClient) ProtocolMapperRepresentation(org.keycloak.representations.idm.ProtocolMapperRepresentation) IDToken(org.keycloak.representations.IDToken) Matchers.isEmptyOrNullString(org.hamcrest.Matchers.isEmptyOrNullString) Map(java.util.Map) HashMap(java.util.HashMap) ProtocolMappersResource(org.keycloak.admin.client.resource.ProtocolMappersResource) AuthServerContainerExclude(org.keycloak.testsuite.arquillian.annotation.AuthServerContainerExclude) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

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