org.keycloak.models.ClientSessionContext Java Examples

The following examples show how to use org.keycloak.models.ClientSessionContext. 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: AudienceResolveProtocolMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    String clientId = clientSessionCtx.getClientSession().getClient().getClientId();

    for (Map.Entry<String, AccessToken.Access> entry : RoleResolveUtil.getAllResolvedClientRoles(session, clientSessionCtx).entrySet()) {
        // Don't add client itself to the audience
        if (entry.getKey().equals(clientId)) {
            continue;
        }

        AccessToken.Access access = entry.getValue();
        if (access != null && access.getRoles() != null && !access.getRoles().isEmpty()) {
            token.addAudience(entry.getKey());
        }
    }

    return token;
}
 
Example #2
Source File: ProtocolMapperUtils.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public static List<Map.Entry<ProtocolMapperModel, ProtocolMapper>> getSortedProtocolMappers(KeycloakSession session, ClientSessionContext ctx) {
    Set<ProtocolMapperModel> mapperModels = ctx.getProtocolMappers();
    Map<ProtocolMapperModel, ProtocolMapper> result = new HashMap<>();

    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    for (ProtocolMapperModel mapperModel : mapperModels) {
        ProtocolMapper mapper = (ProtocolMapper) sessionFactory.getProviderFactory(ProtocolMapper.class, mapperModel.getProtocolMapper());
        if (mapper == null) {
            continue;
        }

        result.put(mapperModel, mapper);
    }

    return result.entrySet()
            .stream()
            .sorted(Comparator.comparing(ProtocolMapperUtils::compare))
            .collect(Collectors.toList());
}
 
Example #3
Source File: SAMLAudienceProtocolMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public ResponseType transformLoginResponse(ResponseType response,
        ProtocolMapperModel mappingModel, KeycloakSession session,
        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    // read configuration as in OIDC (first clientId, then custom)
    String audience = mappingModel.getConfig().get(INCLUDED_CLIENT_AUDIENCE);
    if (audience == null || audience.isEmpty()) {
        audience = mappingModel.getConfig().get(INCLUDED_CUSTOM_AUDIENCE);
    }
    // locate the first condition that has an audience restriction
    if (audience != null && !audience.isEmpty()) {
        AudienceRestrictionType aud = locateAudienceRestriction(response);
        if (aud != null) {
            logger.debugf("adding audience: %s", audience);
            try {
                aud.addAudience(URI.create(audience));
            } catch (IllegalArgumentException e) {
                logger.warnf(e, "Invalid URI syntax for audience: %s", audience);
            }
        }
    }
    return response;
}
 
Example #4
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken transformUserInfoToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                          UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    if (!OIDCAttributeMapperHelper.includeInUserInfo(mappingModel)) {
        return token;
    }

    setClaim(token, mappingModel, userSession, session, clientSessionCtx);
    return token;
}
 
Example #5
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ClientSessionContext attachSession() {
    ClientSessionContext clientSessionCtx = attachSession(authenticationSession, userSession, session, realm, connection, event);

    if (userSession == null) {
        userSession = clientSessionCtx.getClientSession().getUserSession();
    }

    return clientSessionCtx;
}
 
Example #6
Source File: AuthenticationProcessor.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public Response finishAuthentication(LoginProtocol protocol) {
    RealmModel realm = authenticationSession.getRealm();
    ClientSessionContext clientSessionCtx = attachSession();
    event.success();
    return AuthenticationManager.redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, connection, event, authenticationSession, protocol);

}
 
Example #7
Source File: UserRealmRoleMappingMapper.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
@Override
public void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession,
                         KeycloakSession session, ClientSessionContext clientSessionCtx) {
    String rolePrefix = mappingModel.getConfig().get(ProtocolMapperUtils.USER_MODEL_REALM_ROLE_MAPPING_ROLE_PREFIX);

    AccessToken.Access access = RoleResolveUtil.getResolvedRealmRoles(session, clientSessionCtx, false);
    if (access == null) {
        return;
    }

    setAttribute(attributes, mappingModel, access.getRoles(), rolePrefix);
}
 
Example #8
Source File: RoleResolveUtil.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Object (possibly null) containing all the user's realm roles. Including user's groups roles. Composite roles are expanded.
 * Just the roles, which current client has role-scope-mapping for (or it's clientScopes) are included.
 * Current client means the client corresponding to specified clientSessionCtx.
 *
 * @param session
 * @param clientSessionCtx
 * @param createIfMissing
 * @return can return null (just in case that createIfMissing is false)
 */
public static AccessToken.Access getResolvedRealmRoles(KeycloakSession session, ClientSessionContext clientSessionCtx, boolean createIfMissing) {
    AccessToken rolesToken = getAndCacheResolvedRoles(session, clientSessionCtx);
    AccessToken.Access access = rolesToken.getRealmAccess();
    if (access == null && createIfMissing) {
        access = new AccessToken.Access();
        rolesToken.setRealmAccess(access);
    }

    return access;
}
 
Example #9
Source File: SAMLAudienceResolveProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public ResponseType transformLoginResponse(ResponseType response,
        ProtocolMapperModel mappingModel, KeycloakSession session,
        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    // get the audience restriction
    AudienceRestrictionType aud = SAMLAudienceProtocolMapper.locateAudienceRestriction(response);
    if (aud != null) {
        // get all the roles the user has and calculate the clientIds to add
        Set<RoleModel> roles = clientSessionCtx.getRoles();
        Set<String> audiences = new HashSet<>();
        // add as audience any SAML clientId with role included (same as OIDC)
        for (RoleModel role : roles) {
            logger.tracef("Managing role: %s", role.getName());
            if (role.isClientRole()) {
                ClientModel app = (ClientModel) role.getContainer();
                // only adding SAML clients that are not this clientId (which is added by default)
                if (SamlProtocol.LOGIN_PROTOCOL.equals(app.getProtocol()) &&
                        !app.getClientId().equals(clientSessionCtx.getClientSession().getClient().getClientId())) {
                    audiences.add(app.getClientId());
                }
            }
        }
        logger.debugf("Calculated audiences to add: %s", audiences);
        // add the audiences
        for (String audience : audiences) {
            try {
                aud.addAudience(URI.create(audience));
            } catch (IllegalArgumentException e) {
                logger.warnf(e, "Invalid URI syntax for audience: %s", audience);
            }
        }
    }
    return response;
}
 
Example #10
Source File: UserSessionNoteMapper.java    From keycloak-protocol-cas with Apache License 2.0 5 votes vote down vote up
@Override
public void setAttribute(Map<String, Object> attributes, ProtocolMapperModel mappingModel, UserSessionModel userSession,
                         KeycloakSession session, ClientSessionContext clientSessionCt) {
    String noteName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_SESSION_NOTE);
    String noteValue = userSession.getNote(noteName);
    if (noteValue == null) return;
    setMappedAttribute(attributes, mappingModel, noteValue);
}
 
Example #11
Source File: SimpleOidcMapper.java    From keycloak-extension-playground 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) {

    Object claimValue = mappingModel.getConfig().getOrDefault(CONFIG_PROPERTY, "defaultProperty");
    LOGGER.infof("setClaim %s=%s", mappingModel.getName(), claimValue);

    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, claimValue);
}
 
Example #12
Source File: UserSessionManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public boolean isOfflineTokenAllowed(ClientSessionContext clientSessionCtx) {
    RoleModel offlineAccessRole = clientSessionCtx.getClientSession().getRealm().getRole(Constants.OFFLINE_ACCESS_ROLE);
    if (offlineAccessRole == null) {
        ServicesLogger.LOGGER.roleNotInRealm(Constants.OFFLINE_ACCESS_ROLE);
        return false;
    }

    // Check if offline_access is allowed here. Even through composite roles
    return clientSessionCtx.getRoles().contains(offlineAccessRole);
}
 
Example #13
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response redirectAfterSuccessfulFlow(KeycloakSession session, RealmModel realm, UserSessionModel userSession,
                                                   ClientSessionContext clientSessionCtx,
                                            HttpRequest request, UriInfo uriInfo, ClientConnection clientConnection,
                                            EventBuilder event, AuthenticationSessionModel authSession) {
    LoginProtocol protocolImpl = session.getProvider(LoginProtocol.class, authSession.getProtocol());
    protocolImpl.setRealm(realm)
            .setHttpHeaders(request.getHttpHeaders())
            .setUriInfo(uriInfo)
            .setEventBuilder(event);
    return redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, clientConnection, event, authSession, protocolImpl);

}
 
Example #14
Source File: OriginalSubClaimMapper.java    From keycloak-extension-playground with Apache License 2.0 5 votes vote down vote up
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession session, ClientSessionContext clientSessionCtx) {

    RealmModel realm = userSession.getRealm();
    UserModel user = userSession.getUser();

    List<IdentityProviderModel> identityProviders = realm.getIdentityProviders();
    Set<FederatedIdentityModel> identities = session.users().getFederatedIdentities(user, realm);

    if (identityProviders == null || identityProviders.isEmpty()) {
        return;
    }

    for (IdentityProviderModel provider : identityProviders) {
        if (!provider.isEnabled()) {
            continue;
        }

        String providerId = provider.getAlias();
        FederatedIdentityModel identity = getIdentity(identities, providerId);

        if (identity != null) {
            String userId = identity.getUserId();
            OIDCAttributeMapperHelper.mapClaim(token, mappingModel, userId);
        }
    }
}
 
Example #15
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static Response finishedRequiredActions(KeycloakSession session, AuthenticationSessionModel authSession, UserSessionModel userSession,
                                               ClientConnection clientConnection, HttpRequest request, UriInfo uriInfo, EventBuilder event) {
    String actionTokenKeyToInvalidate = authSession.getAuthNote(INVALIDATE_ACTION_TOKEN);
    if (actionTokenKeyToInvalidate != null) {
        ActionTokenKeyModel actionTokenKey = DefaultActionTokenKey.from(actionTokenKeyToInvalidate);
        
        if (actionTokenKey != null) {
            ActionTokenStoreProvider actionTokenStore = session.getProvider(ActionTokenStoreProvider.class);
            actionTokenStore.put(actionTokenKey, null); // Token is invalidated
        }
    }

    if (authSession.getAuthNote(END_AFTER_REQUIRED_ACTIONS) != null) {
        LoginFormsProvider infoPage = session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession)
                .setSuccess(Messages.ACCOUNT_UPDATED);
        if (authSession.getAuthNote(SET_REDIRECT_URI_AFTER_REQUIRED_ACTIONS) != null) {
            if (authSession.getRedirectUri() != null) {
                infoPage.setAttribute("pageRedirectUri", authSession.getRedirectUri());
            }

        } else {
            infoPage.setAttribute(Constants.SKIP_LINK, true);
        }
        Response response = infoPage
                .createInfoPage();

        new AuthenticationSessionManager(session).removeAuthenticationSession(authSession.getRealm(), authSession, true);

        return response;
    }
    RealmModel realm = authSession.getRealm();

    ClientSessionContext clientSessionCtx = AuthenticationProcessor.attachSession(authSession, userSession, session, realm, clientConnection, event);
    userSession = clientSessionCtx.getClientSession().getUserSession();

    event.event(EventType.LOGIN);
    event.session(userSession);
    event.success();
    return redirectAfterSuccessfulFlow(session, realm, userSession, clientSessionCtx, request, uriInfo, clientConnection, event, authSession);
}
 
Example #16
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private AccessToken generateToken(UserModel user, String scopeParam) {
    AuthenticationSessionModel authSession = null;
    UserSessionModel userSession = null;
    AuthenticationSessionManager authSessionManager = new AuthenticationSessionManager(session);

    try {
        RootAuthenticationSessionModel rootAuthSession = authSessionManager.createAuthenticationSession(realm, false);
        authSession = rootAuthSession.createAuthenticationSession(client);

        authSession.setAuthenticatedUser(user);
        authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
        authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(uriInfo.getBaseUri(), realm.getName()));
        authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, scopeParam);

        userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, user, user.getUsername(),
                clientConnection.getRemoteAddr(), "example-auth", false, null, null);

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

        TokenManager tokenManager = new TokenManager();

        TokenManager.AccessTokenResponseBuilder responseBuilder = tokenManager.responseBuilder(realm, client, null, session, userSession, clientSessionCtx)
                .generateAccessToken();

        return responseBuilder.getAccessToken();

    } finally {
        if (authSession != null) {
            authSessionManager.removeAuthenticationSession(realm, authSession, false);
        }
        if (userSession != null) {
            session.sessions().removeUserSession(realm, userSession);
        }
    }
}
 
Example #17
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken transformAccessToken(KeycloakSession session, AccessToken token,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    for (Map.Entry<ProtocolMapperModel, ProtocolMapper> entry : ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx)) {
        ProtocolMapperModel mapping = entry.getKey();
        ProtocolMapper mapper = entry.getValue();
        if (mapper instanceof OIDCAccessTokenMapper) {
            token = ((OIDCAccessTokenMapper) mapper).transformAccessToken(token, mapping, session, userSession, clientSessionCtx);
        }
    }

    return token;
}
 
Example #18
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public void transformIDToken(KeycloakSession session, IDToken token,
                                  UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    for (Map.Entry<ProtocolMapperModel, ProtocolMapper> entry : ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx)) {
        ProtocolMapperModel mapping = entry.getKey();
        ProtocolMapper mapper = entry.getValue();

        if (mapper instanceof OIDCIDTokenMapper) {
            token = ((OIDCIDTokenMapper) mapper).transformIDToken(token, mapping, session, userSession, clientSessionCtx);
        }
    }
}
 
Example #19
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected AccessToken initToken(RealmModel realm, ClientModel client, UserModel user, UserSessionModel session,
                                ClientSessionContext clientSessionCtx, UriInfo uriInfo) {
    AccessToken token = new AccessToken();
    token.id(KeycloakModelUtils.generateId());
    token.type(TokenUtil.TOKEN_TYPE_BEARER);
    token.subject(user.getId());
    token.issuedNow();
    token.issuedFor(client.getClientId());

    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();
    token.issuer(clientSession.getNote(OIDCLoginProtocol.ISSUER));
    token.setNonce(clientSessionCtx.getAttribute(OIDCLoginProtocol.NONCE_PARAM, String.class));
    token.setScope(clientSessionCtx.getScopeString());

    // Best effort for "acr" value. Use 0 if clientSession was authenticated through cookie ( SSO )
    // TODO: Add better acr support. See KEYCLOAK-3314
    String acr = (AuthenticationManager.isSSOAuthentication(clientSession)) ? "0" : "1";
    token.setAcr(acr);

    String authTime = session.getNote(AuthenticationManager.AUTH_TIME);
    if (authTime != null) {
        token.setAuthTime(Integer.parseInt(authTime));
    }


    token.setSessionState(session.getId());
    ClientScopeModel offlineAccessScope = KeycloakModelUtils.getClientScopeByName(realm, OAuth2Constants.OFFLINE_ACCESS);
    boolean offlineTokenRequested = offlineAccessScope == null ? false
        : clientSessionCtx.getClientScopeIds().contains(offlineAccessScope.getId());
    token.expiration(getTokenExpiration(realm, client, session, clientSession, offlineTokenRequested));

    return token;
}
 
Example #20
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessTokenResponseBuilder(RealmModel realm, ClientModel client, EventBuilder event, KeycloakSession session,
                                  UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    this.realm = realm;
    this.client = client;
    this.event = event;
    this.session = session;
    this.userSession = userSession;
    this.clientSessionCtx = clientSessionCtx;
}
 
Example #21
Source File: SamlProtocol.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ResponseType transformLoginResponse(List<ProtocolMapperProcessor<SAMLLoginResponseMapper>> mappers, ResponseType response,
        KeycloakSession session, UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    for (ProtocolMapperProcessor<SAMLLoginResponseMapper> processor : mappers) {
        response = processor.mapper.transformLoginResponse(response, processor.model, session, userSession, clientSessionCtx);
    }

    for (Iterator<SamlAuthenticationPreprocessor> it = SamlSessionUtils.getSamlAuthenticationPreprocessorIterator(session); it.hasNext(); ) {
        response = (ResponseType) it.next().beforeSendingResponse(response, clientSessionCtx.getClientSession());
    }

    return response;
}
 
Example #22
Source File: UserRealmRoleMappingMapper.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 session, ClientSessionContext clientSessionCtx) {
    String rolePrefix = mappingModel.getConfig().get(ProtocolMapperUtils.USER_MODEL_REALM_ROLE_MAPPING_ROLE_PREFIX);

    AccessToken.Access access = RoleResolveUtil.getResolvedRealmRoles(session, clientSessionCtx, false);
    if (access == null) {
        return;
    }

    AbstractUserRoleMappingMapper.setClaim(token, mappingModel, access.getRoles(),null, rolePrefix);
}
 
Example #23
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public IDToken transformIDToken(IDToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    if (!OIDCAttributeMapperHelper.includeInIDToken(mappingModel)){
        return token;
    }

    setClaim(token, mappingModel, userSession, session, clientSessionCtx);
    return token;
}
 
Example #24
Source File: AllowedWebOriginsProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {
    ClientModel client = clientSessionCtx.getClientSession().getClient();

    Set<String> allowedOrigins = client.getWebOrigins();
    if (allowedOrigins != null && !allowedOrigins.isEmpty()) {
        token.setAllowedOrigins(WebOriginsUtils.resolveValidWebOrigins(session, client));
    }

    return token;
}
 
Example #25
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 #26
Source File: AudienceProtocolMapper.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) {
    String audienceValue = mappingModel.getConfig().get(INCLUDED_CLIENT_AUDIENCE);

    if (audienceValue == null) {
        // Fallback to custom audience
        audienceValue = mappingModel.getConfig().get(INCLUDED_CUSTOM_AUDIENCE);
    }

    if (audienceValue == null) return;
    token.addAudience(audienceValue);
}
 
Example #27
Source File: AbstractOIDCProtocolMapper.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken transformAccessToken(AccessToken token, ProtocolMapperModel mappingModel, KeycloakSession session,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    if (!OIDCAttributeMapperHelper.includeInAccessToken(mappingModel)){
        return token;
    }

    setClaim(token, mappingModel, userSession, session, clientSessionCtx);
    return token;
}
 
Example #28
Source File: TokenManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public AccessToken transformUserInfoAccessToken(KeycloakSession session, AccessToken token,
                                        UserSessionModel userSession, ClientSessionContext clientSessionCtx) {

    for (Map.Entry<ProtocolMapperModel, ProtocolMapper> entry : ProtocolMapperUtils.getSortedProtocolMappers(session, clientSessionCtx)) {
        ProtocolMapperModel mapping = entry.getKey();
        ProtocolMapper mapper = entry.getValue();

        if (mapper instanceof UserInfoTokenMapper) {
            token = ((UserInfoTokenMapper) mapper).transformUserInfoToken(token, mapping, session, userSession, clientSessionCtx);
        }
    }

    return token;
}
 
Example #29
Source File: AuthenticationManager.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static Response redirectAfterSuccessfulFlow(KeycloakSession session, RealmModel realm, UserSessionModel userSession,
                                                   ClientSessionContext clientSessionCtx,
                                                   HttpRequest request, UriInfo uriInfo, ClientConnection clientConnection,
                                                   EventBuilder event, AuthenticationSessionModel authSession, LoginProtocol protocol) {
    Cookie sessionCookie = getCookie(request.getHttpHeaders().getCookies(), AuthenticationManager.KEYCLOAK_SESSION_COOKIE);
    if (sessionCookie != null) {

        String[] split = sessionCookie.getValue().split("/");
        if (split.length >= 3) {
            String oldSessionId = split[2];
            if (!oldSessionId.equals(userSession.getId())) {
                UserSessionModel oldSession = session.sessions().getUserSession(realm, oldSessionId);
                if (oldSession != null) {
                    logger.debugv("Removing old user session: session: {0}", oldSessionId);
                    session.sessions().removeUserSession(realm, oldSession);
                }
            }
        }
    }

    // Updates users locale if required
    session.getContext().resolveLocale(userSession.getUser());

    // refresh the cookies!
    createLoginCookie(session, realm, userSession.getUser(), userSession, uriInfo, clientConnection);
    if (userSession.getState() != UserSessionModel.State.LOGGED_IN) userSession.setState(UserSessionModel.State.LOGGED_IN);
    if (userSession.isRememberMe()) {
        createRememberMeCookie(realm, userSession.getLoginUsername(), uriInfo, clientConnection);
    } else {
        expireRememberMeCookie(realm, uriInfo, clientConnection);
    }

    AuthenticatedClientSessionModel clientSession = clientSessionCtx.getClientSession();

    // Update userSession note with authTime. But just if flag SSO_AUTH is not set
    boolean isSSOAuthentication = "true".equals(session.getAttribute(SSO_AUTH));
    if (isSSOAuthentication) {
        clientSession.setNote(SSO_AUTH, "true");
    } else {
        int authTime = Time.currentTime();
        userSession.setNote(AUTH_TIME, String.valueOf(authTime));
        clientSession.removeNote(SSO_AUTH);
    }

    // The user has successfully logged in and we can clear his/her previous login failure attempts.
    logSuccess(session, authSession);

    return protocol.authenticated(authSession, userSession, clientSessionCtx);

}
 
Example #30
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;
}