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);
}
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());
}
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);
}
}
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();
}
}
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);
}
Aggregations