Search in sources :

Example 1 with AuthenticationSessionManager

use of org.keycloak.services.managers.AuthenticationSessionManager in project keycloak by keycloak.

the class OIDCLoginProtocol method sendError.

@Override
public Response sendError(AuthenticationSessionModel authSession, Error error) {
    if (isOAuth2DeviceVerificationFlow(authSession)) {
        return denyOAuth2DeviceAuthorization(authSession, error, session);
    }
    String responseTypeParam = authSession.getClientNote(OIDCLoginProtocol.RESPONSE_TYPE_PARAM);
    String responseModeParam = authSession.getClientNote(OIDCLoginProtocol.RESPONSE_MODE_PARAM);
    setupResponseTypeAndMode(responseTypeParam, responseModeParam);
    String redirect = authSession.getRedirectUri();
    String state = authSession.getClientNote(OIDCLoginProtocol.STATE_PARAM);
    OIDCRedirectUriBuilder redirectUri = OIDCRedirectUriBuilder.fromUri(redirect, responseMode, session, null);
    if (error != Error.CANCELLED_AIA_SILENT) {
        redirectUri.addParam(OAuth2Constants.ERROR, translateError(error));
    }
    if (error == Error.CANCELLED_AIA) {
        redirectUri.addParam(OAuth2Constants.ERROR_DESCRIPTION, "User cancelled aplication-initiated action.");
    }
    if (state != null) {
        redirectUri.addParam(OAuth2Constants.STATE, state);
    }
    new AuthenticationSessionManager(session).removeAuthenticationSession(realm, authSession, true);
    return redirectUri.build();
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) OIDCRedirectUriBuilder(org.keycloak.protocol.oidc.utils.OIDCRedirectUriBuilder)

Example 2 with AuthenticationSessionManager

use of org.keycloak.services.managers.AuthenticationSessionManager in project keycloak by keycloak.

the class AuthorizationEndpointBase method createAuthenticationSession.

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(realm, userSessionId);
                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;
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) UserModel(org.keycloak.models.UserModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionCrossDCManager(org.keycloak.services.managers.UserSessionCrossDCManager)

Example 3 with AuthenticationSessionManager

use of org.keycloak.services.managers.AuthenticationSessionManager in project keycloak by keycloak.

the class ClientScopeEvaluateResource method sessionAware.

private <R> R sessionAware(UserModel user, String scopeParam, BiFunction<UserSessionModel, ClientSessionContext, R> function) {
    AuthenticationSessionModel authSession = 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);
        UserSessionModel userSession = session.sessions().createUserSession(authSession.getParentSession().getId(), realm, user, user.getUsername(), clientConnection.getRemoteAddr(), "example-auth", false, null, null, UserSessionModel.SessionPersistenceState.TRANSIENT);
        AuthenticationManager.setClientScopesInSession(authSession);
        ClientSessionContext clientSessionCtx = TokenManager.attachAuthenticationSession(session, userSession, authSession);
        return function.apply(userSession, clientSessionCtx);
    } finally {
        if (authSession != null) {
            authSessionManager.removeAuthenticationSession(realm, authSession, false);
        }
    }
}
Also used : AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel) UserSessionModel(org.keycloak.models.UserSessionModel) ClientSessionContext(org.keycloak.models.ClientSessionContext) RootAuthenticationSessionModel(org.keycloak.sessions.RootAuthenticationSessionModel)

Example 4 with AuthenticationSessionManager

use of org.keycloak.services.managers.AuthenticationSessionManager in project keycloak by keycloak.

the class IdpVerifyAccountLinkActionTokenHandler method handleToken.

@Override
public Response handleToken(IdpVerifyAccountLinkActionToken token, ActionTokenContext<IdpVerifyAccountLinkActionToken> tokenContext) {
    UserModel user = tokenContext.getAuthenticationSession().getAuthenticatedUser();
    EventBuilder event = tokenContext.getEvent();
    final UriInfo uriInfo = tokenContext.getUriInfo();
    final RealmModel realm = tokenContext.getRealm();
    final KeycloakSession session = tokenContext.getSession();
    event.event(EventType.IDENTITY_PROVIDER_LINK_ACCOUNT).detail(Details.EMAIL, user.getEmail()).detail(Details.IDENTITY_PROVIDER, token.getIdentityProviderAlias()).detail(Details.IDENTITY_PROVIDER_USERNAME, token.getIdentityProviderUsername()).success();
    AuthenticationSessionModel authSession = tokenContext.getAuthenticationSession();
    if (tokenContext.isAuthenticationSessionFresh()) {
        token.setOriginalCompoundAuthenticationSessionId(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_ACCOUNT_LINKING, token.getIdentityProviderUsername(), token.getIdentityProviderAlias()).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);
    if (token.getOriginalCompoundAuthenticationSessionId() != null) {
        AuthenticationSessionManager asm = new AuthenticationSessionManager(session);
        asm.removeAuthenticationSession(realm, authSession, true);
        AuthenticationSessionCompoundId compoundId = AuthenticationSessionCompoundId.encoded(token.getOriginalCompoundAuthenticationSessionId());
        ClientModel originalClient = realm.getClientById(compoundId.getClientUUID());
        authSession = asm.getAuthenticationSessionByIdAndClient(realm, compoundId.getRootSessionId(), originalClient, compoundId.getTabId());
        if (authSession != null) {
            authSession.setAuthNote(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername());
        } else {
            session.authenticationSessions().updateNonlocalSessionAuthNotes(compoundId, Collections.singletonMap(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername()));
        }
        return session.getProvider(LoginFormsProvider.class).setAuthenticationSession(authSession).setSuccess(Messages.IDENTITY_PROVIDER_LINK_SUCCESS, token.getIdentityProviderAlias(), token.getIdentityProviderUsername()).setAttribute(Constants.SKIP_LINK, true).createInfoPage();
    }
    authSession.setAuthNote(IdpEmailVerificationAuthenticator.VERIFY_ACCOUNT_IDP_USERNAME, token.getIdentityProviderUsername());
    return tokenContext.brokerFlow(null, null, authSession.getAuthNote(AuthenticationProcessor.CURRENT_FLOW_PATH));
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) AuthenticationSessionManager(org.keycloak.services.managers.AuthenticationSessionManager) ClientModel(org.keycloak.models.ClientModel) AuthenticationSessionModel(org.keycloak.sessions.AuthenticationSessionModel) KeycloakSession(org.keycloak.models.KeycloakSession) UriBuilder(javax.ws.rs.core.UriBuilder) AuthenticationSessionCompoundId(org.keycloak.sessions.AuthenticationSessionCompoundId) UriInfo(javax.ws.rs.core.UriInfo)

Example 5 with AuthenticationSessionManager

use of org.keycloak.services.managers.AuthenticationSessionManager 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)

Aggregations

AuthenticationSessionManager (org.keycloak.services.managers.AuthenticationSessionManager)22 AuthenticationSessionModel (org.keycloak.sessions.AuthenticationSessionModel)18 RootAuthenticationSessionModel (org.keycloak.sessions.RootAuthenticationSessionModel)15 UserSessionModel (org.keycloak.models.UserSessionModel)11 ClientModel (org.keycloak.models.ClientModel)10 UserModel (org.keycloak.models.UserModel)8 ClientSessionContext (org.keycloak.models.ClientSessionContext)7 GET (javax.ws.rs.GET)4 Response (javax.ws.rs.core.Response)4 UriBuilder (javax.ws.rs.core.UriBuilder)4 LoginFormsProvider (org.keycloak.forms.login.LoginFormsProvider)4 DefaultClientSessionContext (org.keycloak.services.util.DefaultClientSessionContext)4 URI (java.net.URI)3 HashMap (java.util.HashMap)3 Path (javax.ws.rs.Path)3 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)3 TokenManager (org.keycloak.protocol.oidc.TokenManager)3 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)3 IOException (java.io.IOException)2 Map (java.util.Map)2