Search in sources :

Example 36 with UserModel

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

the class ConditionalRoleAuthenticator method matchCondition.

@Override
public boolean matchCondition(AuthenticationFlowContext context) {
    UserModel user = context.getUser();
    RealmModel realm = context.getRealm();
    AuthenticatorConfigModel authConfig = context.getAuthenticatorConfig();
    if (user != null && authConfig != null && authConfig.getConfig() != null) {
        String requiredRole = authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONDITIONAL_USER_ROLE);
        boolean negateOutput = Boolean.parseBoolean(authConfig.getConfig().get(ConditionalRoleAuthenticatorFactory.CONF_NEGATE));
        RoleModel role = KeycloakModelUtils.getRoleFromString(realm, requiredRole);
        if (role == null) {
            logger.errorv("Invalid role name submitted: {0}", requiredRole);
            return false;
        }
        return negateOutput != user.hasRole(role);
    }
    return false;
}
Also used : UserModel(org.keycloak.models.UserModel) RealmModel(org.keycloak.models.RealmModel) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) RoleModel(org.keycloak.models.RoleModel)

Example 37 with UserModel

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

the class RegistrationProfile method success.

@Override
public void success(FormContext context) {
    UserModel user = context.getUser();
    UserProfileProvider provider = context.getSession().getProvider(UserProfileProvider.class);
    provider.create(UserProfileContext.REGISTRATION_PROFILE, context.getHttpRequest().getDecodedFormParameters(), user).update();
}
Also used : UserModel(org.keycloak.models.UserModel) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider)

Example 38 with UserModel

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

the class RegistrationUserCreation method success.

@Override
public void success(FormContext context) {
    MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
    String email = formData.getFirst(UserModel.EMAIL);
    String username = formData.getFirst(UserModel.USERNAME);
    if (context.getRealm().isRegistrationEmailAsUsername()) {
        username = email;
    }
    context.getEvent().detail(Details.USERNAME, username).detail(Details.REGISTER_METHOD, "form").detail(Details.EMAIL, email);
    KeycloakSession session = context.getSession();
    UserProfileProvider profileProvider = session.getProvider(UserProfileProvider.class);
    UserProfile profile = profileProvider.create(UserProfileContext.REGISTRATION_USER_CREATION, formData);
    UserModel user = profile.create();
    user.setEnabled(true);
    context.setUser(user);
    context.getAuthenticationSession().setClientNote(OIDCLoginProtocol.LOGIN_HINT_PARAM, username);
    context.getEvent().user(user);
    context.getEvent().success();
    context.newEvent().event(EventType.LOGIN);
    context.getEvent().client(context.getAuthenticationSession().getClient().getClientId()).detail(Details.REDIRECT_URI, context.getAuthenticationSession().getRedirectUri()).detail(Details.AUTH_METHOD, context.getAuthenticationSession().getProtocol());
    String authType = context.getAuthenticationSession().getAuthNote(Details.AUTH_TYPE);
    if (authType != null) {
        context.getEvent().detail(Details.AUTH_TYPE, authType);
    }
}
Also used : UserModel(org.keycloak.models.UserModel) UserProfile(org.keycloak.userprofile.UserProfile) KeycloakSession(org.keycloak.models.KeycloakSession) UserProfileProvider(org.keycloak.userprofile.UserProfileProvider)

Example 39 with UserModel

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

the class X509ClientCertificateAuthenticator method authenticate.

@Override
public void authenticate(AuthenticationFlowContext context) {
    try {
        dumpContainerAttributes(context);
        X509Certificate[] certs = getCertificateChain(context);
        if (certs == null || certs.length == 0) {
            // No x509 client cert, fall through and
            // continue processing the rest of the authentication flow
            logger.debug("[X509ClientCertificateAuthenticator:authenticate] x509 client certificate is not available for mutual SSL.");
            context.attempted();
            return;
        }
        saveX509CertificateAuditDataToAuthSession(context, certs[0]);
        recordX509CertificateAuditDataViaContextEvent(context);
        X509AuthenticatorConfigModel config = null;
        if (context.getAuthenticatorConfig() != null && context.getAuthenticatorConfig().getConfig() != null) {
            config = new X509AuthenticatorConfigModel(context.getAuthenticatorConfig());
        }
        if (config == null) {
            logger.warn("[X509ClientCertificateAuthenticator:authenticate] x509 Client Certificate Authentication configuration is not available.");
            context.challenge(createInfoResponse(context, "X509 client authentication has not been configured yet"));
            context.attempted();
            return;
        }
        // Validate X509 client certificate
        try {
            CertificateValidator.CertificateValidatorBuilder builder = certificateValidationParameters(context.getSession(), config);
            CertificateValidator validator = builder.build(certs);
            validator.checkRevocationStatus().validateTrust().validateKeyUsage().validateExtendedKeyUsage().validatePolicy().validateTimestamps();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            // TODO use specific locale to load error messages
            String errorMessage = "Certificate validation's failed.";
            // TODO is calling form().setErrors enough to show errors on login screen?
            context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, e.getMessage()));
            context.attempted();
            return;
        }
        Object userIdentity = getUserIdentityExtractor(config).extractUserIdentity(certs);
        if (userIdentity == null) {
            context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
            logger.warnf("[X509ClientCertificateAuthenticator:authenticate] Unable to extract user identity from certificate.");
            // TODO use specific locale to load error messages
            String errorMessage = "Unable to extract user identity from specified certificate";
            // TODO is calling form().setErrors enough to show errors on login screen?
            context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage));
            context.attempted();
            return;
        }
        UserModel user;
        try {
            context.getEvent().detail(Details.USERNAME, userIdentity.toString());
            context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, userIdentity.toString());
            user = getUserIdentityToModelMapper(config).find(context, userIdentity);
        } catch (ModelDuplicateException e) {
            logger.modelDuplicateException(e);
            String errorMessage = "X509 certificate authentication's failed.";
            // TODO is calling form().setErrors enough to show errors on login screen?
            context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, e.getMessage()));
            context.attempted();
            return;
        }
        if (invalidUser(context, user)) {
            // TODO use specific locale to load error messages
            String errorMessage = "X509 certificate authentication's failed.";
            // TODO is calling form().setErrors enough to show errors on login screen?
            context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, "Invalid user"));
            context.attempted();
            return;
        }
        String bruteForceError = getDisabledByBruteForceEventError(context.getProtector(), context.getSession(), context.getRealm(), user);
        if (bruteForceError != null) {
            context.getEvent().user(user);
            context.getEvent().error(bruteForceError);
            // TODO use specific locale to load error messages
            String errorMessage = "X509 certificate authentication's failed.";
            // TODO is calling form().setErrors enough to show errors on login screen?
            context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, "Invalid user"));
            context.attempted();
            return;
        }
        if (!userEnabled(context, user)) {
            // TODO use specific locale to load error messages
            String errorMessage = "X509 certificate authentication's failed.";
            // TODO is calling form().setErrors enough to show errors on login screen?
            context.challenge(createErrorResponse(context, certs[0].getSubjectDN().getName(), errorMessage, "User is disabled"));
            context.attempted();
            return;
        }
        context.setUser(user);
        // Check whether to display the identity confirmation
        if (!config.getConfirmationPageDisallowed()) {
            // FIXME calling forceChallenge was the only way to display
            // a form to let users either choose the user identity from certificate
            // or to ignore it and proceed to a normal login screen. Attempting
            // to call the method "challenge" results in a wrong/unexpected behavior.
            // The question is whether calling "forceChallenge" here is ok from
            // the design viewpoint?
            context.forceChallenge(createSuccessResponse(context, certs[0].getSubjectDN().getName()));
        // Do not set the flow status yet, we want to display a form to let users
        // choose whether to accept the identity from certificate or to specify username/password explicitly
        } else {
            // Bypass the confirmation page and log the user in
            context.success();
        }
    } catch (Exception e) {
        logger.errorf("[X509ClientCertificateAuthenticator:authenticate] Exception: %s", e.getMessage());
        context.attempted();
    }
}
Also used : UserModel(org.keycloak.models.UserModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) X509Certificate(java.security.cert.X509Certificate) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Example 40 with UserModel

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

the class WebAuthnAuthenticator method authenticate.

public void authenticate(AuthenticationFlowContext context) {
    LoginFormsProvider form = context.form();
    Challenge challenge = new DefaultChallenge();
    String challengeValue = Base64Url.encode(challenge.getValue());
    context.getAuthenticationSession().setAuthNote(WebAuthnConstants.AUTH_CHALLENGE_NOTE, challengeValue);
    form.setAttribute(WebAuthnConstants.CHALLENGE, challengeValue);
    WebAuthnPolicy policy = getWebAuthnPolicy(context);
    String rpId = getRpID(context);
    form.setAttribute(WebAuthnConstants.RP_ID, rpId);
    form.setAttribute(WebAuthnConstants.CREATE_TIMEOUT, policy.getCreateTimeout());
    UserModel user = context.getUser();
    boolean isUserIdentified = false;
    if (user != null) {
        // in 2 Factor Scenario where the user has already been identified
        WebAuthnAuthenticatorsBean authenticators = new WebAuthnAuthenticatorsBean(context.getSession(), context.getRealm(), user, getCredentialType());
        if (authenticators.getAuthenticators().isEmpty()) {
            // require the user to register webauthn authenticator
            return;
        }
        isUserIdentified = true;
        form.setAttribute(WebAuthnConstants.ALLOWED_AUTHENTICATORS, authenticators);
    } else {
    // in ID-less & Password-less Scenario
    // NOP
    }
    form.setAttribute(WebAuthnConstants.IS_USER_IDENTIFIED, Boolean.toString(isUserIdentified));
    // read options from policy
    String userVerificationRequirement = policy.getUserVerificationRequirement();
    form.setAttribute(WebAuthnConstants.USER_VERIFICATION, userVerificationRequirement);
    form.setAttribute(WebAuthnConstants.SHOULD_DISPLAY_AUTHENTICATORS, shouldDisplayAuthenticators(context));
    context.challenge(form.createLoginWebAuthn());
}
Also used : UserModel(org.keycloak.models.UserModel) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) WebAuthnPolicy(org.keycloak.models.WebAuthnPolicy) WebAuthnAuthenticatorsBean(org.keycloak.forms.login.freemarker.model.WebAuthnAuthenticatorsBean) Challenge(com.webauthn4j.data.client.challenge.Challenge) DefaultChallenge(com.webauthn4j.data.client.challenge.DefaultChallenge)

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