Search in sources :

Example 41 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 42 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 43 with IDToken

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());
}
Also used : User(com.vsct.vboard.models.User) JsonWebTokenAuthentication(com.vsct.vboard.config.cognito.JsonWebTokenAuthentication) IDToken(org.keycloak.representations.IDToken) KeycloakPrincipal(org.keycloak.KeycloakPrincipal) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) NotNull(javax.validation.constraints.NotNull)

Example 44 with IDToken

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;
    }
}
Also used : AccessToken(org.keycloak.representations.AccessToken) JWSInputException(org.keycloak.jose.jws.JWSInputException) VerificationException(org.keycloak.common.VerificationException) IDToken(org.keycloak.representations.IDToken) JWSInput(org.keycloak.jose.jws.JWSInput) KeycloakPrincipal(org.keycloak.KeycloakPrincipal)

Example 45 with IDToken

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;
}
Also used : AdapterTokenVerifier(org.keycloak.adapters.rotation.AdapterTokenVerifier) AccessToken(org.keycloak.representations.AccessToken) VerificationException(org.keycloak.common.VerificationException) IDToken(org.keycloak.representations.IDToken) IOException(java.io.IOException) AccessTokenResponse(org.keycloak.representations.AccessTokenResponse)

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