Search in sources :

Example 6 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class VerifyEmailActionTokenHandler method handleToken.

@Override
public Response handleToken(VerifyEmailActionToken token, ActionTokenContext<VerifyEmailActionToken> tokenContext) {
    UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
    EventBuilder event = tokenContext.getEvent();
    event.event(EventType.VERIFY_EMAIL).detail(Details.EMAIL, user.getEmail());
    AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
    final UriInfo uriInfo = tokenContext.getUriInfo();
    final RealmModel realm = tokenContext.getRealm();
    final KeycloakSession session = tokenContext.getSession();
    if (tokenContext.isAuthenticationSessionFresh()) {
        // Update the authentication session in the token
        token.setCompoundOriginalAuthenticationSessionId(token.getCompoundAuthenticationSessionId());
        String authSessionEncodedId = AuthenticationSessionCompoundId.fromAuthSession(authSession).getEncodedId();
        token.setCompoundAuthenticationSessionId(authSessionEncodedId);
        UriBuilder builder = Urls.actionTokenBuilder(uriInfo.getBaseUri(), token.serialize(session, realm, uriInfo), authSession.getClient().getClientId(), authSession.getTabId());
        String confirmUri = builder.build(realm.getName()).toString();
        return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.CONFIRM_EMAIL_ADDRESS_VERIFICATION, user.getEmail()).setAttribute(Constants.TEMPLATE_ATTR_ACTION_URI, confirmUri).createInfoPage();
    }
    // verify user email as we know it is valid as this entry point would never have gotten here.
    user.setEmailVerified(true);
    user.removeRequiredAction(RequiredAction.VERIFY_EMAIL);
    authSession.removeRequiredAction(RequiredAction.VERIFY_EMAIL);
    event.success();
    if (token.getCompoundOriginalAuthenticationSessionId() != null) {
        AuthenticationSessionManager asm = new AuthenticationSessionManager(tokenContext.getSession());
        asm.removeAuthenticationSession(tokenContext.getRealm(), authSession, true);
        return tokenContext.getSession().getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.EMAIL_VERIFIED).createInfoPage();
    }
    tokenContext.setEvent(event.clone().removeDetail(Details.EMAIL).event(EventType.LOGIN));
    String nextAction = AuthenticationManager.nextRequiredAction(session, authSession, tokenContext.getRequest(), event);
    return AuthenticationManager.redirectToRequiredActions(session, realm, authSession, uriInfo, nextAction);
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) KeycloakSession(org.keycloak.models.KeycloakSession) UriBuilder(javax.ws.rs.core.UriBuilder) UriInfo(javax.ws.rs.core.UriInfo)

Example 7 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class AbstractIdpAuthenticator method action.

@Override
public void action(AuthenticationFlowContext context) {
    AuthenticationSessionModel clientSession = context.getAuthenticationSession();
    SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(clientSession, BROKERED_CONTEXT_NOTE);
    if (serializedCtx == null) {
        throw new AuthenticationFlowException("Not found serialized context in clientSession", AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }
    BrokeredIdentityContext brokerContext = serializedCtx.deserialize(context.getSession(), clientSession);
    if (!brokerContext.getIdpConfig().isEnabled()) {
        sendFailureChallenge(context, Response.Status.BAD_REQUEST, Errors.IDENTITY_PROVIDER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, AuthenticationFlowError.IDENTITY_PROVIDER_ERROR);
    }
    actionImpl(context, serializedCtx, brokerContext);
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) SerializedBrokeredIdentityContext(org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext)

Example 8 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class IdpConfirmLinkAuthenticator method actionImpl.

@Override
protected void actionImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String action = formData.getFirst("submitAction");
    if (action != null && action.equals("updateProfile")) {
        context.resetFlow(() -> {
            AuthenticationSessionModel authSession = context.getAuthenticationSession();
            serializedCtx.saveToAuthenticationSession(authSession, BROKERED_CONTEXT_NOTE);
            authSession.setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        });
    } else if (action != null && action.equals("linkAccount")) {
        context.success();
    } else {
        throw new AuthenticationFlowException("Unknown action: " + action, AuthenticationFlowError.INTERNAL_ERROR);
    }
}
Also used : AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException)

Example 9 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class IdpConfirmLinkAuthenticator method authenticateImpl.

@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    AuthenticationSessionModel authSession = context.getAuthenticationSession();
    String existingUserInfo = authSession.getAuthNote(EXISTING_USER_INFO);
    if (existingUserInfo == null) {
        ServicesLogger.LOGGER.noDuplicationDetected();
        context.attempted();
        return;
    }
    ExistingUserInfo duplicationInfo = ExistingUserInfo.deserialize(existingUserInfo);
    Response challenge = context.form().setStatus(Response.Status.OK).setAttribute(LoginFormsProvider.IDENTITY_PROVIDER_BROKER_CONTEXT, brokerContext).setError(Messages.FEDERATED_IDENTITY_CONFIRM_LINK_MESSAGE, duplicationInfo.getDuplicateAttributeName(), duplicationInfo.getDuplicateAttributeValue()).createIdpLinkConfirmLinkPage();
    context.challenge(challenge);
}
Also used : Response(javax.ws.rs.core.Response) ExistingUserInfo(org.keycloak.authentication.authenticators.broker.util.ExistingUserInfo) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel)

Example 10 with AuthenticationSessionModel

use of org.keycloak.sessions.AuthenticationSessionModel in project keycloak by keycloak.

the class CibaGrantType method createUserSession.

private UserSessionModel createUserSession(CIBAAuthenticationRequest request, Map<String, String> additionalParams) {
    RootAuthenticationSessionModel rootAuthSession = session.authenticationSessions().createRootAuthenticationSession(realm);
    // here Client Model of CD(Consumption Device) needs to be used to bind its Client Session with User Session.
    AuthenticationSessionModel authSession = rootAuthSession.createAuthenticationSession(client);
    authSession.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL);
    authSession.setAction(AuthenticatedClientSessionModel.Action.AUTHENTICATE.name());
    authSession.setClientNote(OIDCLoginProtocol.ISSUER, Urls.realmIssuer(session.getContext().getUri().getBaseUri(), realm.getName()));
    authSession.setClientNote(OIDCLoginProtocol.SCOPE_PARAM, request.getScope());
    if (additionalParams != null) {
        for (String paramName : additionalParams.keySet()) {
            authSession.setClientNote(ADDITIONAL_CALLBACK_PARAMS_PREFIX + paramName, additionalParams.get(paramName));
        }
    }
    if (request.getOtherClaims() != null) {
        for (String paramName : request.getOtherClaims().keySet()) {
            authSession.setClientNote(ADDITIONAL_BACKCHANNEL_REQ_PARAMS_PREFIX + paramName, request.getOtherClaims().get(paramName).toString());
        }
    }
    UserModel user = session.users().getUserById(realm, request.getSubject());
    if (user == null) {
        event.error(Errors.USERNAME_MISSING);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Could not identify user", Response.Status.BAD_REQUEST);
    }
    if (!user.isEnabled()) {
        event.error(Errors.USER_DISABLED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
    }
    logger.debugf("CIBA Grant :: user model found. user.getId() = %s, user.getEmail() = %s, user.getUsername() = %s.", user.getId(), user.getEmail(), user.getUsername());
    authSession.setAuthenticatedUser(user);
    if (user.getRequiredActionsStream().count() > 0) {
        event.error(Errors.RESOLVE_REQUIRED_ACTIONS);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "Account is not fully set up", Response.Status.BAD_REQUEST);
    }
    AuthenticationManager.setClientScopesInSession(authSession);
    ClientSessionContext context = AuthenticationProcessor.attachSession(authSession, null, session, realm, session.getContext().getConnection(), event);
    UserSessionModel userSession = context.getClientSession().getUserSession();
    if (userSession == null) {
        event.error(Errors.USER_SESSION_NOT_FOUND);
        throw new ErrorResponseException(OAuthErrorException.INVALID_GRANT, "User session is not found", Response.Status.BAD_REQUEST);
    }
    // authorization (consent)
    UserConsentModel grantedConsent = session.users().getConsentByClient(realm, user.getId(), client.getId());
    if (grantedConsent == null) {
        grantedConsent = new UserConsentModel(client);
        session.users().addConsent(realm, user.getId(), grantedConsent);
        if (logger.isTraceEnabled()) {
            grantedConsent.getGrantedClientScopes().forEach(i -> logger.tracef("CIBA Grant :: Consent granted. %s", i.getName()));
        }
    }
    boolean updateConsentRequired = false;
    for (String clientScopeId : authSession.getClientScopes()) {
        ClientScopeModel clientScope = KeycloakModelUtils.findClientScopeById(realm, client, clientScopeId);
        if (clientScope != null && !grantedConsent.isClientScopeGranted(clientScope) && clientScope.isDisplayOnConsentScreen()) {
            grantedConsent.addGrantedClientScope(clientScope);
            updateConsentRequired = true;
        }
    }
    if (updateConsentRequired) {
        session.users().updateConsent(realm, user.getId(), grantedConsent);
        if (logger.isTraceEnabled()) {
            grantedConsent.getGrantedClientScopes().forEach(i -> logger.tracef("CIBA Grant :: Consent updated. %s", i.getName()));
        }
    }
    event.detail(Details.CONSENT, Details.CONSENT_VALUE_CONSENT_GRANTED);
    event.detail(Details.CODE_ID, userSession.getId());
    event.session(userSession.getId());
    event.user(user);
    logger.debugf("Successfully verified Authe Req Id '%s'. User session: '%s', client: '%s'", request, userSession.getId(), client.getId());
    return userSession;
}
Also used : UserModel(org.keycloak.models.UserModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) ClientScopeModel(org.keycloak.models.ClientScopeModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) UserConsentModel(org.keycloak.models.UserConsentModel)

Aggregations

AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)89 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)48 ClientModel (org.keycloak.models.ClientModel)27 UserModel (org.keycloak.models.UserModel)24 Response (javax.ws.rs.core.Response)23 RealmModel (org.keycloak.models.RealmModel)20 UserSessionModel (org.keycloak.models.UserSessionModel)20 AuthenticationSessionManager (org.keycloak.services.managers.AuthenticationSessionManager)18 KeycloakSession (org.keycloak.models.KeycloakSession)16 ClientSessionContext (org.keycloak.models.ClientSessionContext)13 LoginFormsProvider (org.keycloak.forms.login.LoginFormsProvider)10 URI (java.net.URI)9 UriBuilder (javax.ws.rs.core.UriBuilder)9 EventBuilder (org.keycloak.events.EventBuilder)9 LoginProtocol (org.keycloak.protocol.LoginProtocol)9 GET (javax.ws.rs.GET)8 Path (javax.ws.rs.Path)8 AuthenticationFlowException (org.keycloak.authentication.AuthenticationFlowException)8 OIDCLoginProtocol (org.keycloak.protocol.oidc.OIDCLoginProtocol)8 Map (java.util.Map)7