Java Code Examples for org.keycloak.models.KeycloakSession#setAttribute()

The following examples show how to use org.keycloak.models.KeycloakSession#setAttribute() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static IdentityCookieToken createIdentityToken(KeycloakSession keycloakSession, RealmModel realm, UserModel user, UserSessionModel session, String issuer) {
    IdentityCookieToken token = new IdentityCookieToken();
    token.id(KeycloakModelUtils.generateId());
    token.issuedNow();
    token.subject(user.getId());
    token.issuer(issuer);
    token.type(TokenUtil.TOKEN_TYPE_KEYCLOAK_ID);

    if (session != null) {
        token.setSessionState(session.getId());
    }

    if (session != null && session.isRememberMe() && realm.getSsoSessionMaxLifespanRememberMe() > 0) {
        token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespanRememberMe());
    } else if (realm.getSsoSessionMaxLifespan() > 0) {
        token.expiration(Time.currentTime() + realm.getSsoSessionMaxLifespan());
    }

    String stateChecker = (String) keycloakSession.getAttribute("state_checker");
    if (stateChecker == null) {
        stateChecker = Base64Url.encode(KeycloakModelUtils.generateSecret());
        keycloakSession.setAttribute("state_checker", stateChecker);
    }
    token.getOtherClaims().put("state_checker", stateChecker);

    return token;
}
 
Example 2
Source File: UserStorageManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static UserStorageProvider getStorageProviderInstance(KeycloakSession session, UserStorageProviderModel model, UserStorageProviderFactory factory) {
    UserStorageProvider instance = (UserStorageProvider)session.getAttribute(model.getId());
    if (instance != null) return instance;
    instance = factory.create(session, model);
    if (instance == null) {
        throw new IllegalStateException("UserStorageProvideFactory (of type " + factory.getClass().getName() + ") produced a null instance");
    }
    session.enlistForClose(instance);
    session.setAttribute(model.getId(), instance);
    return instance;
}
 
Example 3
Source File: ClientStorageManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ClientStorageProvider getStorageProviderInstance(KeycloakSession session, ClientStorageProviderModel model, ClientStorageProviderFactory factory) {
    ClientStorageProvider instance = (ClientStorageProvider)session.getAttribute(model.getId());
    if (instance != null) return instance;
    instance = factory.create(session, model);
    if (instance == null) {
        throw new IllegalStateException("ClientStorageProvideFactory (of type " + factory.getClass().getName() + ") produced a null instance");
    }
    session.enlistForClose(instance);
    session.setAttribute(model.getId(), instance);
    return instance;
}
 
Example 4
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static AuthResult verifyIdentityToken(KeycloakSession session, RealmModel realm, UriInfo uriInfo, ClientConnection connection, boolean checkActive, boolean checkTokenType,
                                                boolean isCookie, String tokenString, HttpHeaders headers, Predicate<? super AccessToken>... additionalChecks) {
    try {
        TokenVerifier<AccessToken> verifier = TokenVerifier.create(tokenString, AccessToken.class)
          .withDefaultChecks()
          .realmUrl(Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()))
          .checkActive(checkActive)
          .checkTokenType(checkTokenType)
          .withChecks(additionalChecks);
        String kid = verifier.getHeader().getKeyId();
        String algorithm = verifier.getHeader().getAlgorithm().name();

        SignatureVerifierContext signatureVerifier = session.getProvider(SignatureProvider.class, algorithm).verifier(kid);
        verifier.verifierContext(signatureVerifier);

        AccessToken token = verifier.verify().getToken();
        if (checkActive) {
            if (!token.isActive() || token.getIssuedAt() < realm.getNotBefore()) {
                logger.debug("Identity cookie expired");
                return null;
            }
        }

        UserSessionModel userSession = session.sessions().getUserSession(realm, token.getSessionState());
        UserModel user = null;
        if (userSession != null) {
            user = userSession.getUser();
            if (user == null || !user.isEnabled()) {
                logger.debug("Unknown user in identity token");
                return null;
            }

            int userNotBefore = session.users().getNotBeforeOfUser(realm, user);
            if (token.getIssuedAt() < userNotBefore) {
                logger.debug("User notBefore newer than token");
                return null;
            }
        }

        if (!isSessionValid(realm, userSession)) {
            // Check if accessToken was for the offline session.
            if (!isCookie) {
                UserSessionModel offlineUserSession = session.sessions().getOfflineUserSession(realm, token.getSessionState());
                if (isOfflineSessionValid(realm, offlineUserSession)) {
                    user = offlineUserSession.getUser();
                    return new AuthResult(user, offlineUserSession, token);
                }
            }

            if (userSession != null) backchannelLogout(session, realm, userSession, uriInfo, connection, headers, true);
            logger.debug("User session not active");
            return null;
        }

        session.setAttribute("state_checker", token.getOtherClaims().get("state_checker"));

        return new AuthResult(user, userSession, token);
    } catch (VerificationException e) {
        logger.debugf("Failed to verify identity token: %s", e.getMessage());
    }
    return null;
}