Java Code Examples for org.keycloak.models.UserModel#setEmailVerified()

The following examples show how to use org.keycloak.models.UserModel#setEmailVerified() . 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: RemoteUserFederationProvider.java    From keycloak-user-migration-provider with Apache License 2.0 5 votes vote down vote up
private UserModel createUserModel(RealmModel realm, String rawUsername) throws NotFoundException {

        String username = rawUsername.toLowerCase().trim();
        FederatedUserModel remoteUser = federatedUserService.getUserDetails(username);
        LOG.infof("Creating user model for: %s", username);
        UserModel userModel = session.userStorage().addUser(realm, username);

        if (!username.equals(remoteUser.getEmail())) {
            throw new IllegalStateException(String.format("Local and remote users differ: [%s != %s]", username, remoteUser.getUsername()));
        }

        userModel.setFederationLink(model.getId());
        userModel.setEnabled(remoteUser.isEnabled());
        userModel.setEmail(username);
        userModel.setEmailVerified(remoteUser.isEmailVerified());
        userModel.setFirstName(remoteUser.getFirstName());
        userModel.setLastName(remoteUser.getLastName());

        if (remoteUser.getAttributes() != null) {
            Map<String, List<String>> attributes = remoteUser.getAttributes();
            for (String attributeName : attributes.keySet())
                userModel.setAttribute(attributeName, attributes.get(attributeName));
        }

        if (remoteUser.getRoles() != null) {
            for (String role : remoteUser.getRoles()) {
                RoleModel roleModel = realm.getRole(role);
                if (roleModel != null) {
                    userModel.grantRole(roleModel);
                    LOG.infof("Granted user %s, role %s", username, role);
                }
            }
        }

        return userModel;
    }
 
Example 2
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static UserModel createUser(KeycloakSession session, RealmModel newRealm, UserRepresentation userRep) {
    convertDeprecatedSocialProviders(userRep);

    // Import users just to user storage. Don't federate
    UserModel user = session.userLocalStorage().addUser(newRealm, userRep.getId(), userRep.getUsername(), false, false);
    user.setEnabled(userRep.isEnabled() != null && userRep.isEnabled());
    user.setCreatedTimestamp(userRep.getCreatedTimestamp());
    user.setEmail(userRep.getEmail());
    if (userRep.isEmailVerified() != null) user.setEmailVerified(userRep.isEmailVerified());
    user.setFirstName(userRep.getFirstName());
    user.setLastName(userRep.getLastName());
    user.setFederationLink(userRep.getFederationLink());
    if (userRep.getAttributes() != null) {
        for (Map.Entry<String, List<String>> entry : userRep.getAttributes().entrySet()) {
            List<String> value = entry.getValue();
            if (value != null) {
                user.setAttribute(entry.getKey(), new ArrayList<>(value));
            }
        }
    }
    if (userRep.getRequiredActions() != null) {
        for (String requiredAction : userRep.getRequiredActions()) {
            try {
                user.addRequiredAction(UserModel.RequiredAction.valueOf(requiredAction.toUpperCase()));
            } catch (IllegalArgumentException iae) {
                user.addRequiredAction(requiredAction);
            }
        }
    }
    createCredentials(userRep, session, newRealm, user, false);
    createFederatedIdentities(userRep, session, newRealm, user);
    createRoleMappings(userRep, user, newRealm);
    if (userRep.getClientConsents() != null) {
        for (UserConsentRepresentation consentRep : userRep.getClientConsents()) {
            UserConsentModel consentModel = toModel(newRealm, consentRep);
            session.users().addConsent(newRealm, user.getId(), consentModel);
        }
    }

    if (userRep.getNotBefore() != null) {
        session.users().setNotBeforeForUser(newRealm, user, userRep.getNotBefore());
    }

    if (userRep.getServiceAccountClientId() != null) {
        String clientId = userRep.getServiceAccountClientId();
        ClientModel client = newRealm.getClientByClientId(clientId);
        if (client == null) {
            throw new RuntimeException("Unable to find client specified for service account link. Client: " + clientId);
        }
        user.setServiceAccountClientLink(client.getId());
    }
    createGroups(userRep, newRealm, user);
    return user;
}
 
Example 3
Source File: IdpVerifyAccountLinkActionTokenHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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));
}
 
Example 4
Source File: VerifyEmailActionTokenHandler.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@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.getClientConnection(), tokenContext.getRequest(), uriInfo, event);
    return AuthenticationManager.redirectToRequiredActions(session, realm, authSession, uriInfo, nextAction);
}
 
Example 5
Source File: IdentityBrokerService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
private Response afterFirstBrokerLogin(ClientSessionCode<AuthenticationSessionModel> clientSessionCode) {
    AuthenticationSessionModel authSession = clientSessionCode.getClientSession();
    try {
        this.event.detail(Details.CODE_ID, authSession.getParentSession().getId())
                .removeDetail("auth_method");

        SerializedBrokeredIdentityContext serializedCtx = SerializedBrokeredIdentityContext.readFromAuthenticationSession(authSession, AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);
        if (serializedCtx == null) {
            throw new IdentityBrokerException("Not found serialized context in clientSession");
        }
        BrokeredIdentityContext context = serializedCtx.deserialize(session, authSession);
        String providerId = context.getIdpConfig().getAlias();

        event.detail(Details.IDENTITY_PROVIDER, providerId);
        event.detail(Details.IDENTITY_PROVIDER_USERNAME, context.getUsername());

        // Ensure the first-broker-login flow was successfully finished
        String authProvider = authSession.getAuthNote(AbstractIdpAuthenticator.FIRST_BROKER_LOGIN_SUCCESS);
        if (authProvider == null || !authProvider.equals(providerId)) {
            throw new IdentityBrokerException("Invalid request. Not found the flag that first-broker-login flow was finished");
        }

        // firstBrokerLogin workflow finished. Removing note now
        authSession.removeAuthNote(AbstractIdpAuthenticator.BROKERED_CONTEXT_NOTE);

        UserModel federatedUser = authSession.getAuthenticatedUser();
        if (federatedUser == null) {
            throw new IdentityBrokerException("Couldn't found authenticated federatedUser in authentication session");
        }

        event.user(federatedUser);
        event.detail(Details.USERNAME, federatedUser.getUsername());

        if (context.getIdpConfig().isAddReadTokenRoleOnCreate()) {
            ClientModel brokerClient = realmModel.getClientByClientId(Constants.BROKER_SERVICE_CLIENT_ID);
            if (brokerClient == null) {
                throw new IdentityBrokerException("Client 'broker' not available. Maybe realm has not migrated to support the broker token exchange service");
            }
            RoleModel readTokenRole = brokerClient.getRole(Constants.READ_TOKEN_ROLE);
            federatedUser.grantRole(readTokenRole);
        }

        // Add federated identity link here
        FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(),
                context.getUsername(), context.getToken());
        session.users().addFederatedIdentity(realmModel, federatedUser, federatedIdentityModel);


        String isRegisteredNewUser = authSession.getAuthNote(AbstractIdpAuthenticator.BROKER_REGISTERED_NEW_USER);
        if (Boolean.parseBoolean(isRegisteredNewUser)) {

            logger.debugf("Registered new user '%s' after first login with identity provider '%s'. Identity provider username is '%s' . ", federatedUser.getUsername(), providerId, context.getUsername());

            context.getIdp().importNewUser(session, realmModel, federatedUser, context);
            Set<IdentityProviderMapperModel> mappers = realmModel.getIdentityProviderMappersByAlias(providerId);
            if (mappers != null) {
                KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
                for (IdentityProviderMapperModel mapper : mappers) {
                    IdentityProviderMapper target = (IdentityProviderMapper)sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
                    target.importNewUser(session, realmModel, federatedUser, mapper, context);
                }
            }

            if (context.getIdpConfig().isTrustEmail() && !Validation.isBlank(federatedUser.getEmail()) && !Boolean.parseBoolean(authSession.getAuthNote(AbstractIdpAuthenticator.UPDATE_PROFILE_EMAIL_CHANGED))) {
                logger.debugf("Email verified automatically after registration of user '%s' through Identity provider '%s' ", federatedUser.getUsername(), context.getIdpConfig().getAlias());
                federatedUser.setEmailVerified(true);
            }

            event.event(EventType.REGISTER)
                    .detail(Details.REGISTER_METHOD, "broker")
                    .detail(Details.EMAIL, federatedUser.getEmail())
                    .success();

        } else {
            logger.debugf("Linked existing keycloak user '%s' with identity provider '%s' . Identity provider username is '%s' .", federatedUser.getUsername(), providerId, context.getUsername());

            event.event(EventType.FEDERATED_IDENTITY_LINK)
                    .success();

            updateFederatedIdentity(context, federatedUser);
        }

        return finishOrRedirectToPostBrokerLogin(authSession, context, true, clientSessionCode);

    }  catch (Exception e) {
        return redirectToErrorPage(authSession, Response.Status.INTERNAL_SERVER_ERROR, Messages.IDENTITY_PROVIDER_UNEXPECTED_ERROR, e);
    }
}