Search in sources :

Example 6 with UserModel

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

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

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

the class AbstractIdpAuthenticator method getExistingUser.

public static UserModel getExistingUser(KeycloakSession session, RealmModel realm, AuthenticationSessionModel authSession) {
    String existingUserId = authSession.getAuthNote(EXISTING_USER_INFO);
    if (existingUserId == null) {
        throw new AuthenticationFlowException("Unexpected state. There is no existing duplicated user identified in ClientSession", AuthenticationFlowError.INTERNAL_ERROR);
    }
    ExistingUserInfo duplication = ExistingUserInfo.deserialize(existingUserId);
    UserModel existingUser = session.users().getUserById(realm, duplication.getExistingUserId());
    if (existingUser == null) {
        throw new AuthenticationFlowException("User with ID '" + existingUserId + "' not found.", AuthenticationFlowError.INVALID_USER);
    }
    if (!existingUser.isEnabled()) {
        throw new AuthenticationFlowException("User with ID '" + existingUserId + "', username '" + existingUser.getUsername() + "' disabled.", AuthenticationFlowError.USER_DISABLED);
    }
    return existingUser;
}
Also used : UserModel(org.keycloak.models.UserModel) ExistingUserInfo(org.keycloak.authentication.authenticators.broker.util.ExistingUserInfo) AuthenticationFlowException(org.keycloak.authentication.AuthenticationFlowException)

Example 9 with UserModel

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

the class DeviceGrantType method oauth2DeviceFlow.

public Response oauth2DeviceFlow() {
    if (!realm.getOAuth2DeviceConfig().isOAuth2DeviceAuthorizationGrantEnabled(client)) {
        event.error(Errors.NOT_ALLOWED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Client not allowed OAuth 2.0 Device Authorization Grant", Response.Status.BAD_REQUEST);
    }
    String deviceCode = formParams.getFirst(OAuth2Constants.DEVICE_CODE);
    if (deviceCode == null) {
        event.error(Errors.INVALID_OAUTH2_DEVICE_CODE);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_REQUEST, "Missing parameter: " + OAuth2Constants.DEVICE_CODE, Response.Status.BAD_REQUEST);
    }
    OAuth2DeviceTokenStoreProvider store = session.getProvider(OAuth2DeviceTokenStoreProvider.class);
    OAuth2DeviceCodeModel deviceCodeModel = store.getByDeviceCode(realm, deviceCode);
    if (deviceCodeModel == null) {
        event.error(Errors.INVALID_OAUTH2_DEVICE_CODE);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Device code not valid", Response.Status.BAD_REQUEST);
    }
    if (deviceCodeModel.isExpired()) {
        event.error(Errors.EXPIRED_OAUTH2_DEVICE_CODE);
        throw new CorsErrorResponseException(cors, OAuthErrorException.EXPIRED_TOKEN, "Device code is expired", Response.Status.BAD_REQUEST);
    }
    if (!store.isPollingAllowed(deviceCodeModel)) {
        event.error(Errors.SLOW_DOWN);
        throw new CorsErrorResponseException(cors, OAuthErrorException.SLOW_DOWN, "Slow down", Response.Status.BAD_REQUEST);
    }
    if (deviceCodeModel.isDenied()) {
        event.error(Errors.ACCESS_DENIED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.ACCESS_DENIED, "The end user denied the authorization request", Response.Status.BAD_REQUEST);
    }
    if (deviceCodeModel.isPending()) {
        throw new CorsErrorResponseException(cors, OAuthErrorException.AUTHORIZATION_PENDING, "The authorization request is still pending", Response.Status.BAD_REQUEST);
    }
    // https://tools.ietf.org/html/rfc7636#section-4.6
    String codeVerifier = formParams.getFirst(OAuth2Constants.CODE_VERIFIER);
    String codeChallenge = deviceCodeModel.getCodeChallenge();
    String codeChallengeMethod = deviceCodeModel.getCodeChallengeMethod();
    if (codeChallengeMethod != null && !codeChallengeMethod.isEmpty()) {
        PkceUtils.checkParamsForPkceEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, null, null, event, cors);
    } else {
        // PKCE Activation is OFF, execute the codes implemented in KEYCLOAK-2604
        PkceUtils.checkParamsForPkceNotEnforcedClient(codeVerifier, codeChallenge, codeChallengeMethod, null, null, event, cors);
    }
    // Approved
    String userSessionId = deviceCodeModel.getUserSessionId();
    event.detail(Details.CODE_ID, userSessionId);
    event.session(userSessionId);
    // Retrieve UserSession
    UserSessionModel userSession = new UserSessionCrossDCManager(session).getUserSessionWithClient(realm, userSessionId, client.getId());
    if (userSession == null) {
        userSession = session.sessions().getUserSession(realm, userSessionId);
        if (userSession == null) {
            throw new CorsErrorResponseException(cors, OAuthErrorException.AUTHORIZATION_PENDING, "The authorization request is verified but can not lookup the user session yet", Response.Status.BAD_REQUEST);
        }
    }
    // Now, remove the device code
    store.removeDeviceCode(realm, deviceCode);
    UserModel user = userSession.getUser();
    if (user == null) {
        event.error(Errors.USER_NOT_FOUND);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User not found", Response.Status.BAD_REQUEST);
    }
    event.user(userSession.getUser());
    if (!user.isEnabled()) {
        event.error(Errors.USER_DISABLED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "User disabled", Response.Status.BAD_REQUEST);
    }
    AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessionByClient(client.getId());
    if (!client.getClientId().equals(clientSession.getClient().getClientId())) {
        event.error(Errors.INVALID_CODE);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Auth error", Response.Status.BAD_REQUEST);
    }
    if (!AuthenticationManager.isSessionValid(realm, userSession)) {
        event.error(Errors.USER_SESSION_NOT_FOUND);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, "Session not active", Response.Status.BAD_REQUEST);
    }
    try {
        session.clientPolicy().triggerOnEvent(new DeviceTokenRequestContext(deviceCodeModel, formParams));
    } catch (ClientPolicyException cpe) {
        event.error(cpe.getError());
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_GRANT, cpe.getErrorDetail(), Response.Status.BAD_REQUEST);
    }
    // Compute client scopes again from scope parameter. Check if user still has them granted
    // (but in device_code-to-token request, it could just theoretically happen that they are not available)
    String scopeParam = deviceCodeModel.getScope();
    if (!TokenManager.verifyConsentStillAvailable(session, user, client, TokenManager.getRequestedClientScopes(scopeParam, client))) {
        event.error(Errors.NOT_ALLOWED);
        throw new CorsErrorResponseException(cors, OAuthErrorException.INVALID_SCOPE, "Client no longer has requested consent from user", Response.Status.BAD_REQUEST);
    }
    ClientSessionContext clientSessionCtx = DefaultClientSessionContext.fromClientSessionAndScopeParameter(clientSession, scopeParam, session);
    // Set nonce as an attribute in the ClientSessionContext. Will be used for the token generation
    clientSessionCtx.setAttribute(OIDCLoginProtocol.NONCE_PARAM, deviceCodeModel.getNonce());
    return tokenEndpoint.createTokenResponse(user, userSession, clientSessionCtx, scopeParam, false);
}
Also used : OAuth2DeviceTokenStoreProvider(org.keycloak.models.OAuth2DeviceTokenStoreProvider) UserModel(org.keycloak.models.UserModel) UserSessionModel(org.keycloak.models.UserSessionModel) DeviceTokenRequestContext(org.keycloak.protocol.oidc.grants.device.clientpolicy.context.DeviceTokenRequestContext) DefaultClientSessionContext(org.keycloak.services.util.DefaultClientSessionContext) ClientSessionContext(org.keycloak.models.ClientSessionContext) OAuth2DeviceCodeModel(org.keycloak.models.OAuth2DeviceCodeModel) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) UserSessionCrossDCManager(org.keycloak.services.managers.UserSessionCrossDCManager) ClientPolicyException(org.keycloak.services.clientpolicy.ClientPolicyException)

Example 10 with UserModel

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

the class AddressMapper method setClaim.

@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);
}
Also used : UserModel(org.keycloak.models.UserModel) AddressClaimSet(org.keycloak.representations.AddressClaimSet)

Aggregations

UserModel (org.keycloak.models.UserModel)383 RealmModel (org.keycloak.models.RealmModel)220 Test (org.junit.Test)126 ClientModel (org.keycloak.models.ClientModel)86 KeycloakSession (org.keycloak.models.KeycloakSession)81 CachedUserModel (org.keycloak.models.cache.CachedUserModel)52 ModelTest (org.keycloak.testsuite.arquillian.annotation.ModelTest)43 List (java.util.List)41 UserSessionModel (org.keycloak.models.UserSessionModel)40 AbstractTestRealmKeycloakTest (org.keycloak.testsuite.AbstractTestRealmKeycloakTest)40 RoleModel (org.keycloak.models.RoleModel)39 ComponentModel (org.keycloak.component.ComponentModel)31 HashMap (java.util.HashMap)30 Response (javax.ws.rs.core.Response)29 Path (javax.ws.rs.Path)28 UserManager (org.keycloak.models.UserManager)28 LDAPObject (org.keycloak.storage.ldap.idm.model.LDAPObject)27 Map (java.util.Map)25 GroupModel (org.keycloak.models.GroupModel)24 AbstractAuthTest (org.keycloak.testsuite.AbstractAuthTest)24