Search in sources :

Example 6 with RealmModel

use of org.keycloak.models.RealmModel in project keycloak by keycloak.

the class IdpDetectExistingBrokerUserAuthenticator method authenticateImpl.

@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {
    RealmModel realm = context.getRealm();
    if (context.getAuthenticationSession().getAuthNote(EXISTING_USER_INFO) != null) {
        context.attempted();
        return;
    }
    String username = getUsername(context, serializedCtx, brokerContext);
    if (username == null) {
        ServicesLogger.LOGGER.resetFlow(realm.isRegistrationEmailAsUsername() ? "Email" : "Username");
        context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
        context.resetFlow();
        return;
    }
    ExistingUserInfo duplication = checkExistingUser(context, username, serializedCtx, brokerContext);
    if (duplication == null) {
        logger.errorf("The user %s should be already registered in the realm to login %s", username, realm.getName());
        Response challengeResponse = context.form().setError(Messages.FEDERATED_IDENTITY_UNAVAILABLE, username, brokerContext.getIdpConfig().getAlias()).createErrorPage(Response.Status.UNAUTHORIZED);
        context.challenge(challengeResponse);
        context.getEvent().detail("authenticator", "DetectExistingBrokerUser").removeDetail(Details.AUTH_METHOD).removeDetail(Details.AUTH_TYPE).error(Errors.USER_NOT_FOUND);
    } else {
        logger.debugf("Duplication detected. There is already existing user with %s '%s' .", duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue());
        // Set duplicated user, so next authenticators can deal with it
        context.getAuthenticationSession().setAuthNote(EXISTING_USER_INFO, duplication.serialize());
        context.success();
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) Response(javax.ws.rs.core.Response) ExistingUserInfo(org.keycloak.authentication.authenticators.broker.util.ExistingUserInfo)

Example 7 with RealmModel

use of org.keycloak.models.RealmModel 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 8 with RealmModel

use of org.keycloak.models.RealmModel 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 9 with RealmModel

use of org.keycloak.models.RealmModel in project keycloak by keycloak.

the class DeviceGrantType method denyOAuth2DeviceAuthorization.

public static Response denyOAuth2DeviceAuthorization(AuthenticationSessionModel authSession, LoginProtocol.Error error, KeycloakSession session) {
    KeycloakContext context = session.getContext();
    RealmModel realm = context.getRealm();
    KeycloakUriInfo uri = context.getUri();
    UriBuilder uriBuilder = DeviceGrantType.oauth2DeviceVerificationCompletedUrl(uri);
    String errorType = OAuthErrorException.SERVER_ERROR;
    if (error == LoginProtocol.Error.CONSENT_DENIED) {
        String verifiedUserCode = authSession.getClientNote(DeviceGrantType.OAUTH2_DEVICE_VERIFIED_USER_CODE);
        OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
        if (!store.deny(realm, verifiedUserCode)) {
            // Already expired and removed in the store
            errorType = OAuthErrorException.EXPIRED_TOKEN;
        } else {
            errorType = OAuthErrorException.ACCESS_DENIED;
        }
    }
    return Response.status(302).location(uriBuilder.queryParam(OAuth2Constants.ERROR, errorType).build(realm.getName())).build();
}
Also used : RealmModel(org.keycloak.models.RealmModel) OAuth2DeviceTokenStoreProvider(org.keycloak.models.OAuth2DeviceTokenStoreProvider) KeycloakUriInfo(org.keycloak.models.KeycloakUriInfo) KeycloakContext(org.keycloak.models.KeycloakContext) UriBuilder(javax.ws.rs.core.UriBuilder)

Example 10 with RealmModel

use of org.keycloak.models.RealmModel in project keycloak by keycloak.

the class DeviceGrantType method approveOAuth2DeviceAuthorization.

public static Response approveOAuth2DeviceAuthorization(AuthenticationSessionModel authSession, AuthenticatedClientSessionModel clientSession, KeycloakSession session) {
    KeycloakContext context = session.getContext();
    RealmModel realm = context.getRealm();
    KeycloakUriInfo uriInfo = context.getUri();
    UriBuilder uriBuilder = DeviceGrantType.oauth2DeviceVerificationCompletedUrl(uriInfo);
    String verifiedUserCode = authSession.getClientNote(DeviceGrantType.OAUTH2_DEVICE_VERIFIED_USER_CODE);
    String userSessionId = clientSession.getUserSession().getId();
    OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
    if (!store.approve(realm, verifiedUserCode, userSessionId, null)) {
        // Already expired and removed in the store
        return Response.status(302).location(uriBuilder.queryParam(OAuth2Constants.ERROR, OAuthErrorException.EXPIRED_TOKEN).build(realm.getName())).build();
    }
    // Now, remove the verified user code
    store.removeUserCode(realm, verifiedUserCode);
    return Response.status(302).location(uriBuilder.build(realm.getName())).build();
}
Also used : RealmModel(org.keycloak.models.RealmModel) OAuth2DeviceTokenStoreProvider(org.keycloak.models.OAuth2DeviceTokenStoreProvider) KeycloakUriInfo(org.keycloak.models.KeycloakUriInfo) KeycloakContext(org.keycloak.models.KeycloakContext) UriBuilder(javax.ws.rs.core.UriBuilder)

Aggregations

RealmModel (org.keycloak.models.RealmModel)591 Test (org.junit.Test)249 UserModel (org.keycloak.models.UserModel)225 KeycloakSession (org.keycloak.models.KeycloakSession)152 ClientModel (org.keycloak.models.ClientModel)149 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)90 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)84 ComponentModel (org.keycloak.component.ComponentModel)83 RoleModel (org.keycloak.models.RoleModel)73 UserSessionModel (org.keycloak.models.UserSessionModel)64 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)62 List (java.util.List)55 LDAPStorageProvider (org.keycloak.storage.ldap.LDAPStorageProvider)51 GroupModel (org.keycloak.models.GroupModel)47 HashMap (java.util.HashMap)38 Collectors (java.util.stream.Collectors)34 CachedUserModel (org.keycloak.models.cache.CachedUserModel)34 Path (javax.ws.rs.Path)30 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)30 Map (java.util.Map)29