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

The following examples show how to use org.keycloak.models.UserModel#addRequiredAction() . 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: KerberosFederationProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected UserModel importUserToKeycloak(RealmModel realm, String username) {
    // Just guessing email from kerberos realm
    String email = username + "@" + kerberosConfig.getKerberosRealm().toLowerCase();

    logger.debugf("Creating kerberos user: %s, email: %s to local Keycloak storage", username, email);
    UserModel user = session.userLocalStorage().addUser(realm, username);
    user.setEnabled(true);
    user.setEmail(email);
    user.setFederationLink(model.getId());
    user.setSingleAttribute(KERBEROS_PRINCIPAL, username + "@" + kerberosConfig.getKerberosRealm());

    if (kerberosConfig.isUpdateProfileFirstLogin()) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PROFILE);
    }

    return validate(realm, user);
}
 
Example 2
Source File: MSADUserAccountControlStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean processAuthErrorCode(String errorCode, UserModel user) {
    logger.debugf("MSAD Error code is '%s' after failed LDAP login of user '%s'", errorCode, user.getUsername());

    if (ldapProvider.getEditMode() == UserStorageProvider.EditMode.WRITABLE) {
        if (errorCode.equals("532") || errorCode.equals("773")) {
            // User needs to change his MSAD password. Allow him to login, but add UPDATE_PASSWORD required action
            if (!user.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_PASSWORD.name())) {
                user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
            }
            return true;
        } else if (errorCode.equals("533")) {
            // User is disabled in MSAD. Set him to disabled in KC as well
            if (user.isEnabled()) {
                user.setEnabled(false);
            }
            return true;
        } else if (errorCode.equals("775")) {
            logger.warnf("Locked user '%s' attempt to login", user.getUsername());
        }
    }

    return false;
}
 
Example 3
Source File: MSADLDSUserAccountControlStorageMapper.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected boolean processAuthErrorCode(String errorCode, UserModel user) {
    logger.debugf("MSAD LDS Error code is '%s' after failed LDAP login of user '%s'", errorCode, user.getUsername());

    if (ldapProvider.getEditMode() == UserStorageProvider.EditMode.WRITABLE) {
        if (errorCode.equals("532") || errorCode.equals("773")) {
            // User needs to change his MSAD password. Allow him to login, but add UPDATE_PASSWORD required action
            if (!user.getRequiredActions().contains(UserModel.RequiredAction.UPDATE_PASSWORD.name())) {
                user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
            }
            return true;
        } else if (errorCode.equals("533")) {
            // User is disabled in MSAD LDS. Set him to disabled in KC as well
            if (user.isEnabled()) {
                user.setEnabled(false);
            }
            return true;
        } else if (errorCode.equals("775")) {
            logger.warnf("Locked user '%s' attempt to login", user.getUsername());
        }
    }

    return false;
}
 
Example 4
Source File: RegistrationPassword.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void success(FormContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String password = formData.getFirst(RegistrationPage.FIELD_PASSWORD);
    UserModel user = context.getUser();
    try {
        context.getSession().userCredentialManager().updateCredential(context.getRealm(), user, UserCredentialModel.password(formData.getFirst("password"), false));
    } catch (Exception me) {
        user.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
    }

}
 
Example 5
Source File: WebAuthnPasswordlessAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
    // ask the user to do required action to register webauthn authenticator
    if (!user.getRequiredActions().contains(WebAuthnPasswordlessRegisterFactory.PROVIDER_ID)) {
        user.addRequiredAction(WebAuthnPasswordlessRegisterFactory.PROVIDER_ID);
    }
}
 
Example 6
Source File: ConditionalOtpFormAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
    if (!isOTPRequired(session, realm, user)) {
        user.removeRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP);
    } else if (!user.getRequiredActions().contains(UserModel.RequiredAction.CONFIGURE_TOTP.name())) {
        user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP.name());
    }
}
 
Example 7
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 8
Source File: SecretQuestionAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
    user.addRequiredAction(SecretQuestionRequiredAction.PROVIDER_ID);
}
 
Example 9
Source File: OTPFormAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
    if (!user.getRequiredActions().contains(UserModel.RequiredAction.CONFIGURE_TOTP.name())) {
        user.addRequiredAction(UserModel.RequiredAction.CONFIGURE_TOTP.name());
    }
}
 
Example 10
Source File: WebAuthnAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public void setRequiredActions(KeycloakSession session, RealmModel realm, UserModel user) {
    // ask the user to do required action to register webauthn authenticator
    if (!user.getRequiredActions().contains(WebAuthnRegisterFactory.PROVIDER_ID)) {
        user.addRequiredAction(WebAuthnRegisterFactory.PROVIDER_ID);
    }
}
 
Example 11
Source File: IdpCreateUserIfUniqueAuthenticator.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected void authenticateImpl(AuthenticationFlowContext context, SerializedBrokeredIdentityContext serializedCtx, BrokeredIdentityContext brokerContext) {

    KeycloakSession session = context.getSession();
    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.debugf("No duplication detected. Creating account for user '%s' and linking with identity provider '%s' .",
                username, brokerContext.getIdpConfig().getAlias());

        UserModel federatedUser = session.users().addUser(realm, username);
        federatedUser.setEnabled(true);
        federatedUser.setEmail(brokerContext.getEmail());
        federatedUser.setFirstName(brokerContext.getFirstName());
        federatedUser.setLastName(brokerContext.getLastName());

        for (Map.Entry<String, List<String>> attr : serializedCtx.getAttributes().entrySet()) {
            federatedUser.setAttribute(attr.getKey(), attr.getValue());
        }

        AuthenticatorConfigModel config = context.getAuthenticatorConfig();
        if (config != null && Boolean.parseBoolean(config.getConfig().get(IdpCreateUserIfUniqueAuthenticatorFactory.REQUIRE_PASSWORD_UPDATE_AFTER_REGISTRATION))) {
            logger.debugf("User '%s' required to update password", federatedUser.getUsername());
            federatedUser.addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
        }

        userRegisteredSuccess(context, federatedUser, serializedCtx, brokerContext);

        context.setUser(federatedUser);
        context.getAuthenticationSession().setAuthNote(BROKER_REGISTERED_NEW_USER, "true");
        context.success();
    } 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());
        //Only show error message if the authenticator was required
        if (context.getExecution().isRequired()) {
            Response challengeResponse = context.form()
                    .setError(Messages.FEDERATED_IDENTITY_EXISTS, duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .createErrorPage(Response.Status.CONFLICT);
            context.challenge(challengeResponse);
            context.getEvent()
                    .user(duplication.getExistingUserId())
                    .detail("existing_" + duplication.getDuplicateAttributeName(), duplication.getDuplicateAttributeValue())
                    .removeDetail(Details.AUTH_METHOD)
                    .removeDetail(Details.AUTH_TYPE)
                    .error(Errors.FEDERATED_IDENTITY_EXISTS);
        } else {
            context.attempted();
        }
    }
}