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");
}
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();
}
use of org.keycloak.representations.IDToken in project vboard by voyages-sncf-technologies.
the class AuthenticationController method createUserFromAuth.
@NotNull
@SuppressFBWarnings("CLI_CONSTANT_LIST_INDEX")
private static User createUserFromAuth(Authentication auth) {
if (auth instanceof JsonWebTokenAuthentication) {
JsonWebTokenAuthentication jwtAuth = ((JsonWebTokenAuthentication) auth);
String username = jwtAuth.getName();
String[] parts = StringUtils.split(username, "\\");
if (parts != null) {
username = parts[1];
}
parts = StringUtils.split(username, "_");
if (parts == null) {
throw new IllegalArgumentException("The username in the JWT token provided does not contain a '_'");
}
String firstName = StringUtils.capitalize(parts[0]);
String lastName = StringUtils.capitalize(parts[1]);
LOGGER.info("createUserFromAuth/JWT: email={} firstName={} lastName={}", jwtAuth.getEmail(), firstName, lastName);
return new User(jwtAuth.getEmail(), firstName, lastName);
}
final KeycloakPrincipal userDetails = (KeycloakPrincipal) auth.getPrincipal();
final IDToken idToken = userDetails.getKeycloakSecurityContext().getToken();
LOGGER.info("createUserFromAuth/Keycloak: email={} firstName={} lastName={}", idToken.getEmail(), idToken.getGivenName(), idToken.getFamilyName());
return new User(idToken.getEmail(), idToken.getGivenName(), idToken.getFamilyName());
}
use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class CookieTokenStore method getPrincipalFromCookie.
public static KeycloakPrincipal<RefreshableKeycloakSecurityContext> getPrincipalFromCookie(KeycloakDeployment deployment, HttpFacade facade, AdapterTokenStore tokenStore) {
OIDCHttpFacade.Cookie cookie = facade.getRequest().getCookie(AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE);
if (cookie == null) {
log.debug("Not found adapter state cookie in current request");
return null;
}
String cookieVal = cookie.getValue();
String[] tokens = cookieVal.split(DELIM);
if (tokens.length != 3) {
log.warnf("Invalid format of %s cookie. Count of tokens: %s, expected 3", AdapterConstants.KEYCLOAK_ADAPTER_STATE_COOKIE, tokens.length);
return null;
}
String accessTokenString = tokens[0];
String idTokenString = tokens[1];
String refreshTokenString = tokens[2];
try {
// Skip check if token is active now. It's supposed to be done later by the caller
TokenVerifier<AccessToken> tokenVerifier = AdapterTokenVerifier.createVerifier(accessTokenString, deployment, true, AccessToken.class).checkActive(false).verify();
AccessToken accessToken = tokenVerifier.getToken();
IDToken idToken;
if (idTokenString != null && idTokenString.length() > 0) {
try {
JWSInput input = new JWSInput(idTokenString);
idToken = input.readJsonContent(IDToken.class);
} catch (JWSInputException e) {
throw new VerificationException(e);
}
} else {
idToken = null;
}
log.debug("Token Verification succeeded!");
RefreshableKeycloakSecurityContext secContext = new RefreshableKeycloakSecurityContext(deployment, tokenStore, accessTokenString, accessToken, idTokenString, idToken, refreshTokenString);
return new KeycloakPrincipal<>(AdapterUtils.getPrincipalName(deployment, accessToken), secContext);
} catch (VerificationException ve) {
log.warn("Failed verify token", ve);
return null;
}
}
use of org.keycloak.representations.IDToken in project keycloak by keycloak.
the class RefreshableKeycloakSecurityContext method refreshExpiredToken.
/**
* @param checkActive if true, then we won't send refresh request if current accessToken is still active.
* @return true if accessToken is active or was successfully refreshed
*/
public boolean refreshExpiredToken(boolean checkActive) {
if (checkActive) {
if (log.isTraceEnabled()) {
log.trace("checking whether to refresh.");
}
if (isActive() && isTokenTimeToLiveSufficient(this.token))
return true;
}
// Might be serialized in HttpSession?
if (this.deployment == null || refreshToken == null)
return false;
if (!this.getRealm().equals(this.deployment.getRealm())) {
// this should not happen, but let's check it anyway
return false;
}
if (log.isTraceEnabled()) {
log.trace("Doing refresh");
}
//
synchronized (this) {
if (checkActive) {
log.trace("Checking whether token has been refreshed in another thread already.");
if (isActive() && isTokenTimeToLiveSufficient(this.token))
return true;
}
AccessTokenResponse response;
try {
response = ServerRequest.invokeRefresh(deployment, refreshToken);
} catch (IOException e) {
log.error("Refresh token failure", e);
return false;
} catch (ServerRequest.HttpFailure httpFailure) {
final Logger.Level logLevel = httpFailure.getError().contains("Refresh token expired") ? Logger.Level.WARN : Logger.Level.ERROR;
log.log(logLevel, "Refresh token failure status: " + httpFailure.getStatus() + " " + httpFailure.getError());
return false;
}
if (log.isTraceEnabled()) {
log.trace("received refresh response");
}
String tokenString = response.getToken();
AccessToken token = null;
IDToken idToken = null;
try {
AdapterTokenVerifier.VerifiedTokens tokens = AdapterTokenVerifier.verifyTokens(tokenString, response.getIdToken(), deployment);
token = tokens.getAccessToken();
idToken = tokens.getIdToken();
log.debug("Token Verification succeeded!");
} catch (VerificationException e) {
log.error("failed verification of token");
return false;
}
// If the TTL is greater-or-equal to the expire time on the refreshed token, have to abort or go into an infinite refresh loop
if (!isTokenTimeToLiveSufficient(token)) {
log.error("failed to refresh the token with a longer time-to-live than the minimum");
return false;
}
if (response.getNotBeforePolicy() > deployment.getNotBefore()) {
deployment.updateNotBefore(response.getNotBeforePolicy());
}
if (idToken != null) {
this.idToken = idToken;
this.idTokenString = response.getIdToken();
}
this.token = token;
if (response.getRefreshToken() != null) {
if (log.isTraceEnabled()) {
log.trace("Setup new refresh token to the security context");
}
this.refreshToken = response.getRefreshToken();
}
this.tokenString = tokenString;
if (tokenStore != null) {
tokenStore.refreshCallback(this);
}
}
return true;
}
Aggregations