Java Code Examples for org.keycloak.models.UserSessionModel#getUser()

The following examples show how to use org.keycloak.models.UserSessionModel#getUser() . 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: PersistentUserSessionAdapter.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public PersistentUserSessionAdapter(UserSessionModel other) {
    this.data = new PersistentUserSessionData();
    data.setAuthMethod(other.getAuthMethod());
    data.setBrokerSessionId(other.getBrokerSessionId());
    data.setBrokerUserId(other.getBrokerUserId());
    data.setIpAddress(other.getIpAddress());
    data.setNotes(other.getNotes());
    data.setRememberMe(other.isRememberMe());
    if (other.getState() != null) {
        data.setState(other.getState().toString());
    }

    this.model = new PersistentUserSessionModel();
    this.model.setStarted(other.getStarted());
    this.model.setUserSessionId(other.getId());
    this.model.setLastSessionRefresh(other.getLastSessionRefresh());

    this.user = other.getUser();
    this.userId = this.user.getId();
    this.realm = other.getRealm();
    this.authenticatedClientSessions = other.getAuthenticatedClientSessions();
}
 
Example 2
Source File: TokenManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private boolean isUserValid(KeycloakSession session, RealmModel realm, AccessToken token, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    if (user == null) {
        return false;
    }
    if (!user.isEnabled()) {
        return false;
    }
    try {
        TokenVerifier.createWithoutSignature(token)
                .withChecks(NotBeforeCheck.forModel(session ,realm, user))
                .verify();
    } catch (VerificationException e) {
        return false;
    }

    if (token.getIssuedAt() + 1 < userSession.getStarted()) {
        return false;
    }
    return true;
}
 
Example 3
Source File: TokenRevocationEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void checkUser() {
    UserSessionModel userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm,
        token.getSessionState(), false, client.getId());

    if (userSession == null) {
        userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, token.getSessionState(), true,
            client.getId());

        if (userSession == null) {
            event.error(Errors.USER_SESSION_NOT_FOUND);
            throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token",
                Response.Status.OK);
        }
    }

    user = userSession.getUser();

    if (user == null) {
        event.error(Errors.USER_NOT_FOUND);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_TOKEN, "Invalid token", Response.Status.OK);
    }

    event.user(user);
}
 
Example 4
Source File: SamlProtocol.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to retrieve the persistent type NameId as follows:
 *
 * <ol>
 *     <li>saml.persistent.name.id.for.$clientId user attribute</li>
 *     <li>saml.persistent.name.id.for.* user attribute</li>
 *     <li>G-$randomUuid</li>
 * </ol>
 *
 * If a randomUuid is generated, an attribute for the given saml.persistent.name.id.for.$clientId will be generated,
 * otherwise no state change will occur with respect to the user's attributes.
 *
 * @return the user's persistent NameId
 */
protected String getPersistentNameId(final CommonClientSessionModel clientSession, final UserSessionModel userSession) {
    // attempt to retrieve the UserID for the client-specific attribute
    final UserModel user = userSession.getUser();
    final String clientNameId = String.format("%s.%s", SAML_PERSISTENT_NAME_ID_FOR,
            clientSession.getClient().getClientId());
    String samlPersistentNameId = user.getFirstAttribute(clientNameId);
    if (samlPersistentNameId != null) {
        return samlPersistentNameId;
    }

    // check for a wildcard attribute
    final String wildcardNameId = String.format("%s.*", SAML_PERSISTENT_NAME_ID_FOR);
    samlPersistentNameId = user.getFirstAttribute(wildcardNameId);
    if (samlPersistentNameId != null) {
        return samlPersistentNameId;
    }

    // default to generated.  "G-" stands for "generated"
    samlPersistentNameId = "G-" + UUID.randomUUID().toString();
    user.setSingleAttribute(clientNameId, samlPersistentNameId);
    return samlPersistentNameId;
}
 
Example 5
Source File: UserPropertyMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    String propertyName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_ATTRIBUTE);

    if (propertyName == null || propertyName.trim().isEmpty()) return;

    String propertyValue = ProtocolMapperUtils.getUserModelValue(user, propertyName);
    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, propertyValue);
}
 
Example 6
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param session
 * @param realm
 * @param userSession
 * @param uriInfo
 * @param connection
 * @param headers
 * @param logoutBroker
 * @param offlineSession
 */
public static void backchannelLogout(KeycloakSession session, RealmModel realm,
                                     UserSessionModel userSession, UriInfo uriInfo,
                                     ClientConnection connection, HttpHeaders headers,
                                     boolean logoutBroker,
                                     boolean offlineSession) {
    if (userSession == null) return;
    UserModel user = userSession.getUser();
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

    logger.debugv("Logging out: {0} ({1}) offline: {2}", user.getUsername(), userSession.getId(), userSession.isOffline());
    expireUserSessionCookie(session, userSession, realm, uriInfo, headers, connection);

    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, false);

    try {
        backchannelLogoutAll(session, realm, userSession, logoutAuthSession, uriInfo, headers, logoutBroker);
        checkUserSessionOnlyHasLoggedOutClients(realm, userSession, logoutAuthSession);
    } finally {
        RootAuthenticationSessionModel rootAuthSession = logoutAuthSession.getParentSession();
        rootAuthSession.removeAuthenticationSessionByTabId(logoutAuthSession.getTabId());
    }

    userSession.setState(UserSessionModel.State.LOGGED_OUT);

    if (offlineSession) {
        new UserSessionManager(session).revokeOfflineUserSession(userSession);

        // Check if "online" session still exists and remove it too
        UserSessionModel onlineUserSession = session.sessions().getUserSession(realm, userSession.getId());
        if (onlineUserSession != null) {
            session.sessions().removeUserSession(realm, onlineUserSession);
        }
    } else {
        session.sessions().removeUserSession(realm, userSession);
    }
}
 
Example 7
Source File: KeycloakIdentity.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private UserModel getUserFromSessionState() {
    UserSessionProvider sessions = keycloakSession.sessions();
    UserSessionModel userSession = sessions.getUserSession(realm, accessToken.getSessionState());

    if (userSession == null) {
        userSession = sessions.getOfflineUserSession(realm, accessToken.getSessionState());
    }

    return userSession.getUser();
}
 
Example 8
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private Response checkAccountManagementFailedLinking(AuthenticationSessionModel authSession, String error, Object... parameters) {
    UserSessionModel userSession = new AuthenticationSessionManager(session).getUserSession(authSession);
    if (userSession != null && authSession.getClient() != null && authSession.getClient().getClientId().equals(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID)) {

        this.event.event(EventType.FEDERATED_IDENTITY_LINK);
        UserModel user = userSession.getUser();
        this.event.user(user);
        this.event.detail(Details.USERNAME, user.getUsername());

        return redirectToAccountErrorPage(authSession, error, parameters);
    } else {
        return null;
    }
}
 
Example 9
Source File: AuthorizationEndpointBase.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AuthenticationSessionModel createAuthenticationSession(ClientModel client, String requestState) {
    AuthenticationSessionManager manager = new AuthenticationSessionManager(session);
    RootAuthenticationSessionModel rootAuthSession = manager.getCurrentRootAuthenticationSession(realm);

    AuthenticationSessionModel authSession;

    if (rootAuthSession != null) {
        authSession = rootAuthSession.createAuthenticationSession(client);

        logger.debugf("Sent request to authz endpoint. Root authentication session with ID '%s' exists. Client is '%s' . Created new authentication session with tab ID: %s",
                rootAuthSession.getId(), client.getClientId(), authSession.getTabId());
    } else {
        UserSessionCrossDCManager userSessionCrossDCManager = new UserSessionCrossDCManager(session);
        UserSessionModel userSession = userSessionCrossDCManager.getUserSessionIfExistsRemotely(manager, realm);

        if (userSession != null) {
            UserModel user = userSession.getUser();
            if (user != null && !user.isEnabled()) {
                authSession = createNewAuthenticationSession(manager, client);

                AuthenticationManager.backchannelLogout(session, userSession, true);
            } else {
                String userSessionId = userSession.getId();
                rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(userSessionId, realm);
                authSession = rootAuthSession.createAuthenticationSession(client);
                logger.debugf("Sent request to authz endpoint. We don't have root authentication session with ID '%s' but we have userSession." +
                        "Re-created root authentication session with same ID. Client is: %s . New authentication session tab ID: %s", userSessionId, client.getClientId(), authSession.getTabId());
            }
        } else {
            authSession = createNewAuthenticationSession(manager, client);
        }
    }

    session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession);

    return authSession;

}
 
Example 10
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response browserLogout(KeycloakSession session,
                                     RealmModel realm,
                                     UserSessionModel userSession,
                                     UriInfo uriInfo,
                                     ClientConnection connection,
                                     HttpHeaders headers,
                                     String initiatingIdp) {
    if (userSession == null) return null;

    if (logger.isDebugEnabled()) {
        UserModel user = userSession.getUser();
        logger.debugv("Logging out: {0} ({1})", user.getUsername(), userSession.getId());
    }
    
    if (userSession.getState() != UserSessionModel.State.LOGGING_OUT) {
        userSession.setState(UserSessionModel.State.LOGGING_OUT);
    }

    final AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
    AuthenticationSessionModel logoutAuthSession = createOrJoinLogoutSession(session, realm, asm, userSession, true);

    Response response = browserLogoutAllClients(userSession, session, realm, headers, uriInfo, logoutAuthSession);
    if (response != null) {
        return response;
    }

    String brokerId = userSession.getNote(Details.IDENTITY_PROVIDER);
    if (brokerId != null && !brokerId.equals(initiatingIdp)) {
        IdentityProvider identityProvider = IdentityBrokerService.getIdentityProvider(session, realm, brokerId);
        response = identityProvider.keycloakInitiatedBrowserLogout(session, userSession, uriInfo, realm);
        if (response != null) {
            return response;
        }
    }

    return finishBrowserLogout(session, realm, userSession, uriInfo, connection, headers);
}
 
Example 11
Source File: AddressMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    AddressClaimSet addressSet = new AddressClaimSet();
    addressSet.setStreetAddress(getUserModelAttributeValue(user, mappingModel, STREET));
    addressSet.setLocality(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.LOCALITY));
    addressSet.setRegion(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.REGION));
    addressSet.setPostalCode(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.POSTAL_CODE));
    addressSet.setCountry(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.COUNTRY));
    addressSet.setFormattedAddress(getUserModelAttributeValue(user, mappingModel, AddressClaimSet.FORMATTED));
    token.getOtherClaims().put("address", addressSet);
}
 
Example 12
Source File: UserAttributeMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {

        UserModel user = userSession.getUser();
        String attributeName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_ATTRIBUTE);
        boolean aggregateAttrs = Boolean.valueOf(mappingModel.getConfig().get(ProtocolMapperUtils.AGGREGATE_ATTRS));
        Collection<String> attributeValue = KeycloakModelUtils.resolveAttribute(user, attributeName, aggregateAttrs);
        if (attributeValue == null) return;
        OIDCAttributeMapperHelper.mapClaim(token, mappingModel, attributeValue);
    }
 
Example 13
Source File: FullNameMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    List<String> parts = new LinkedList<>();
    Optional.ofNullable(user.getFirstName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    Optional.ofNullable(user.getLastName()).filter(s -> !s.isEmpty()).ifPresent(parts::add);
    if (!parts.isEmpty()) {
        token.getOtherClaims().put("name", String.join(" ", parts));
    }
}
 
Example 14
Source File: ScriptBasedOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx) {

  UserModel user = userSession.getUser();
  String scriptSource = getScriptCode(mappingModel);
  RealmModel realm = userSession.getRealm();

  ScriptingProvider scripting = keycloakSession.getProvider(ScriptingProvider.class);
  ScriptModel scriptModel = scripting.createScript(realm.getId(), ScriptModel.TEXT_JAVASCRIPT, "token-mapper-script_" + mappingModel.getName(), scriptSource, null);

  EvaluatableScriptAdapter script = scripting.prepareEvaluatableScript(scriptModel);

  Object claimValue;
  try {
    claimValue = script.eval((bindings) -> {
      bindings.put("user", user);
      bindings.put("realm", realm);
      bindings.put("token", token);
      bindings.put("userSession", userSession);
      bindings.put("keycloakSession", keycloakSession);
    });
  } catch (Exception ex) {
    LOGGER.error("Error during execution of ProtocolMapper script", ex);
    claimValue = null;
  }

  OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example 15
Source File: RemoteOidcMapper.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
private Object fetchRemoteClaims(ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession) {

        try {
            String remoteUrl = mappingModel.getConfig().getOrDefault(REMOTE_URL_PROPERTY, "http://localhost:7777/claims");
            UserModel user = userSession.getUser();
            String url = remoteUrl + "?userId=" + user.getId() + "&username=" + URLEncoder.encode(user.getUsername(), "UTF-8");
            JsonNode jsonNode = SimpleHttp.doGet(url, keycloakSession).asJson();
            return jsonNode;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
 
Example 16
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;
}
 
Example 17
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static ClientSessionContext attachSession(AuthenticationSessionModel authSession, UserSessionModel userSession, KeycloakSession session, RealmModel realm, ClientConnection connection, EventBuilder event) {
    String username = authSession.getAuthenticatedUser().getUsername();
    String attemptedUsername = authSession.getAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME);
    if (attemptedUsername != null) username = attemptedUsername;
    String rememberMe = authSession.getAuthNote(Details.REMEMBER_ME);
    boolean remember = rememberMe != null && rememberMe.equalsIgnoreCase("true");
    String brokerSessionId = authSession.getAuthNote(BROKER_SESSION_ID);
    String brokerUserId = authSession.getAuthNote(BROKER_USER_ID);

    if (userSession == null) { // if no authenticator attached a usersession

        userSession = session.sessions().getUserSession(realm, authSession.getParentSession().getId());
        if (userSession == null) {
            userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, authSession.getAuthenticatedUser(), username, connection.getRemoteAddr(), authSession.getProtocol()
                    , remember, brokerSessionId, brokerUserId);
        } else if (userSession.getUser() == null || !AuthenticationManager.isSessionValid(realm, userSession)) {
            userSession.restartSession(realm, authSession.getAuthenticatedUser(), username, connection.getRemoteAddr(), authSession.getProtocol()
                    , remember, brokerSessionId, brokerUserId);
        } else {
            // We have existing userSession even if it wasn't attached to authenticator. Could happen if SSO authentication was ignored (eg. prompt=login) and in some other cases.
            // We need to handle case when different user was used
            logger.debugf("No SSO login, but found existing userSession with ID '%s' after finished authentication.", userSession.getId());
            if (!authSession.getAuthenticatedUser().equals(userSession.getUser())) {
                event.detail(Details.EXISTING_USER, userSession.getUser().getId());
                event.error(Errors.DIFFERENT_USER_AUTHENTICATED);
                throw new ErrorPageException(session, authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.DIFFERENT_USER_AUTHENTICATED, userSession.getUser().getUsername());
            }
        }
        userSession.setState(UserSessionModel.State.LOGGED_IN);
    }

    if (remember) {
        event.detail(Details.REMEMBER_ME, "true");
    }

    ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);

    event.user(userSession.getUser())
            .detail(Details.USERNAME, username)
            .session(userSession);

    return clientSessionCtx;
}
 
Example 18
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Response performAccountLinking(AuthenticationSessionModel authSession, UserSessionModel userSession, BrokeredIdentityContext context, FederatedIdentityModel newModel, UserModel federatedUser) {
    logger.debugf("Will try to link identity provider [%s] to user [%s]", context.getIdpConfig().getAlias(), userSession.getUser().getUsername());

    this.event.event(EventType.FEDERATED_IDENTITY_LINK);



    UserModel authenticatedUser = userSession.getUser();
    authSession.setAuthenticatedUser(authenticatedUser);

    if (federatedUser != null && !authenticatedUser.getId().equals(federatedUser.getId())) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.IDENTITY_PROVIDER_ALREADY_LINKED, context.getIdpConfig().getAlias());
    }

    if (!authenticatedUser.hasRole(this.realmModel.getClientByClientId(Constants.ACCOUNT_MANAGEMENT_CLIENT_ID).getRole(AccountRoles.MANAGE_ACCOUNT))) {
        return redirectToErrorPage(authSession, Response.Status.FORBIDDEN, Messages.INSUFFICIENT_PERMISSION);
    }

    if (!authenticatedUser.isEnabled()) {
        return redirectToErrorWhenLinkingFailed(authSession, Messages.ACCOUNT_DISABLED);
    }



    if (federatedUser != null) {
        if (context.getIdpConfig().isStoreToken()) {
            FederatedIdentityModel oldModel = this.session.users().getFederatedIdentity(federatedUser, context.getIdpConfig().getAlias(), this.realmModel);
            if (!ObjectUtil.isEqualOrBothNull(context.getToken(), oldModel.getToken())) {
                this.session.users().updateFederatedIdentity(this.realmModel, federatedUser, newModel);
                if (isDebugEnabled()) {
                    logger.debugf("Identity [%s] update with response from identity provider [%s].", federatedUser, context.getIdpConfig().getAlias());
                }
            }
        }
    } else {
        this.session.users().addFederatedIdentity(this.realmModel, authenticatedUser, newModel);
    }
    context.getIdp().authenticationFinished(authSession, context);

    AuthenticationManager.setClientScopesInSession(authSession);
    TokenManager.attachAuthenticationSession(session, userSession, authSession);

    if (isDebugEnabled()) {
        logger.debugf("Linking account [%s] from identity provider [%s] to user [%s].", newModel, context.getIdpConfig().getAlias(), authenticatedUser);
    }

    this.event.user(authenticatedUser)
            .detail(Details.USERNAME, authenticatedUser.getUsername())
            .detail(Details.IDENTITY_PROVIDER, newModel.getIdentityProvider())
            .detail(Details.IDENTITY_PROVIDER_USERNAME, newModel.getUserName())
            .success();

    // we do this to make sure that the parent IDP is logged out when this user session is complete.
    // But for the case when userSession was previously authenticated with broker1 and now is linked to another broker2, we shouldn't override broker1 notes with the broker2 for sure.
    // Maybe broker logout should be rather always skiped in case of broker-linking
    if (userSession.getNote(Details.IDENTITY_PROVIDER) == null) {
        userSession.setNote(Details.IDENTITY_PROVIDER, context.getIdpConfig().getAlias());
        userSession.setNote(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());
    }

    return Response.status(302).location(UriBuilder.fromUri(authSession.getRedirectUri()).build()).build();
}
 
Example 19
Source File: TokenManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public TokenValidation validateToken(KeycloakSession session, UriInfo uriInfo, ClientConnection connection, RealmModel realm,
                                     RefreshToken oldToken, HttpHeaders headers) throws OAuthErrorException {
    UserSessionModel userSession = null;
    boolean offline = TokenUtil.TOKEN_TYPE_OFFLINE.equals(oldToken.getType());

    if (offline) {

        UserSessionManager sessionManager = new UserSessionManager(session);
        userSession = sessionManager.findOfflineUserSession(realm, oldToken.getSessionState());
        if (userSession != null) {

            // Revoke timeouted offline userSession
            if (!AuthenticationManager.isOfflineSessionValid(realm, userSession)) {
                sessionManager.revokeOfflineUserSession(userSession);
                throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Offline session not active", "Offline session not active");
            }

        } else {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Offline user session not found", "Offline user session not found");
        }
    } else {
        // Find userSession regularly for online tokens
        userSession = session.sessions().getUserSession(realm, oldToken.getSessionState());
        if (!AuthenticationManager.isSessionValid(realm, userSession)) {
            AuthenticationManager.backchannelLogout(session, realm, userSession, uriInfo, connection, headers, true);
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Session not active", "Session not active");
        }
    }

    UserModel user = userSession.getUser();
    if (user == null) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Invalid refresh token", "Unknown user");
    }

    if (!user.isEnabled()) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "User disabled", "User disabled");
    }

    if (oldToken.getIssuedAt() + 1 < userSession.getStarted()) {
        logger.debug("Refresh toked issued before the user session started");
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Refresh toked issued before the user session started");
    }


    ClientModel client = session.getContext().getClient();
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());

    // Can theoretically happen in cross-dc environment. Try to see if userSession with our client is available in remoteCache
    if (clientSession == null) {
        userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, userSession.getId(), offline, client.getId());
        if (userSession != null) {
            clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
        } else {
            throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Session doesn't have required client", "Session doesn't have required client");
        }
    }

    if (!client.getClientId().equals(oldToken.getIssuedFor())) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Unmatching clients", "Unmatching clients");
    }

    try {
        TokenVerifier.createWithoutSignature(oldToken)
                .withChecks(NotBeforeCheck.forModel(client), NotBeforeCheck.forModel(session, realm, user))
                .verify();
    } catch (VerificationException e) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_GRANT, "Stale token");
    }

    // Setup clientScopes from refresh token to the context
    String oldTokenScope = oldToken.getScope();

    // Case when offline token is migrated from previous version
    if (oldTokenScope == null && userSession.isOffline()) {
        logger.debugf("Migrating offline token of user '%s' for client '%s' of realm '%s'", user.getUsername(), client.getClientId(), realm.getName());
        MigrationUtils.migrateOldOfflineToken(session, realm, client, user);
        oldTokenScope = OAuth2Constants.OFFLINE_ACCESS;
    }

    ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession, oldTokenScope, session);

    // Check user didn't revoke granted consent
    if (!verifyConsentStillAvailable(session, user, client, clientSessionCtx.getClientScopes())) {
        throw new OAuthErrorException(OAuthErrorException.INVALID_SCOPE, "Client no longer has requested consent from user");
    }

    clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, oldToken.getNonce());

    // recreate token.
    AccessToken newToken = createClientAccessToken(session, realm, client, user, userSession, clientSessionCtx);

    return new TokenValidation(user, userSession, clientSessionCtx, newToken);
}
 
Example 20
Source File: UserPropertyAttributeStatementMapper.java    From keycloak with Apache License 2.0 3 votes vote down vote up
@Override
public void transformAttributeStatement(AttributeStatementType attributeStatement, ProtocolMapperModel mappingModel, KeycloakSession session, UserSessionModel userSession, AuthenticatedClientSessionModel clientSession) {
    UserModel user = userSession.getUser();
    String propertyName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_ATTRIBUTE);

    if (propertyName == null || propertyName.trim().isEmpty()) return;

    String propertyValue = ProtocolMapperUtils.getUserModelValue(user, propertyName);

    if (propertyValue == null) return;

    AttributeStatementHelper.addAttribute(attributeStatement, mappingModel, propertyValue);
}