Search in sources :

Example 41 with UserModel

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

the class WebAuthnAuthenticator method createErrorResponse.

private Response createErrorResponse(AuthenticationFlowContext context, final String errorCase) {
    LoginFormsProvider provider = context.form().setError(errorCase, "");
    UserModel user = context.getUser();
    if (user != null) {
        WebAuthnAuthenticatorsBean authenticators = new WebAuthnAuthenticatorsBean(context.getSession(), context.getRealm(), user, getCredentialType());
        if (authenticators.getAuthenticators() != null) {
            provider.setAttribute(WebAuthnConstants.ALLOWED_AUTHENTICATORS, authenticators);
        }
    }
    return provider.createWebAuthnErrorPage();
}
Also used : UserModel(org.keycloak.models.UserModel) LoginFormsProvider(org.keycloak.forms.login.LoginFormsProvider) WebAuthnAuthenticatorsBean(org.keycloak.forms.login.freemarker.model.WebAuthnAuthenticatorsBean)

Example 42 with UserModel

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

the class ValidateX509CertificateUsername method authenticate.

@Override
public void authenticate(AuthenticationFlowContext context) {
    X509Certificate[] certs = getCertificateChain(context);
    if (certs == null || certs.length == 0) {
        logger.debug("[ValidateX509CertificateUsername:authenticate] x509 client certificate is not available for mutual SSL.");
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", "X509 client certificate is missing.");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        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("[ValidateX509CertificateUsername:authenticate] x509 Client Certificate Authentication configuration is not available.");
        context.getEvent().error(Errors.USER_NOT_FOUND);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", "Configuration is missing.");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    // Validate X509 client certificate
    try {
        CertificateValidator.CertificateValidatorBuilder builder = certificateValidationParameters(context.getSession(), config);
        CertificateValidator validator = builder.build(certs);
        validator.checkRevocationStatus().validateTrust().validateKeyUsage().validateExtendedKeyUsage().validateTimestamps().validatePolicy();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        // TODO use specific locale to load error messages
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", e.getMessage());
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    Object userIdentity = getUserIdentityExtractor(config).extractUserIdentity(certs);
    if (userIdentity == null) {
        context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
        logger.errorf("[ValidateX509CertificateUsername: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";
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", errorMessage);
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        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 = String.format("X509 certificate authentication's failed. Reason: \"%s\"", e.getMessage());
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", errorMessage);
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        String errorMessage = String.format("X509 certificate authentication's failed. Reason: \"%s\"", e.getMessage());
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", errorMessage);
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    if (user == null) {
        context.getEvent().error(Errors.INVALID_USER_CREDENTIALS);
        Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_grant", "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    String bruteForceError = getDisabledByBruteForceEventError(context.getProtector(), context.getSession(), context.getRealm(), user);
    if (bruteForceError != null) {
        context.getEvent().user(user);
        context.getEvent().error(bruteForceError);
        Response challengeResponse = errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_grant", "Invalid user credentials");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    if (!user.isEnabled()) {
        context.getEvent().user(user);
        context.getEvent().error(Errors.USER_DISABLED);
        Response challengeResponse = errorResponse(Response.Status.BAD_REQUEST.getStatusCode(), "invalid_grant", "Account disabled");
        context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
        return;
    }
    context.setUser(user);
    context.success();
}
Also used : Response(javax.ws.rs.core.Response) UserModel(org.keycloak.models.UserModel) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) X509Certificate(java.security.cert.X509Certificate) ModelDuplicateException(org.keycloak.models.ModelDuplicateException)

Example 43 with UserModel

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

the class RegistrationPassword method success.

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

Example 44 with UserModel

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

the class SamlProtocol method getPersistentNameId.

/**
 * Attempts to retrieve the persistent type NameId as follows:
 *
 * <ol>
 * <li>saml.persistent.name.id.for.$clientId user attribute</li>
 * <li>saml.persistent.name.id.for.* user attribute</li>
 * <li>G-$randomUuid</li>
 * </ol>
 * <p>
 * If a randomUuid is generated, an attribute for the given saml.persistent.name.id.for.$clientId will be generated,
 * otherwise no state change will occur with respect to the user's attributes.
 *
 * @return the user's persistent NameId
 */
protected String getPersistentNameId(final CommonClientSessionModel clientSession, final UserSessionModel userSession) {
    // attempt to retrieve the UserID for the client-specific attribute
    final UserModel user = userSession.getUser();
    final String clientNameId = String.format("%s.%s", SAML_PERSISTENT_NAME_ID_FOR, clientSession.getClient().getClientId());
    String samlPersistentNameId = user.getFirstAttribute(clientNameId);
    if (samlPersistentNameId != null) {
        return samlPersistentNameId;
    }
    // check for a wildcard attribute
    final String wildcardNameId = String.format("%s.*", SAML_PERSISTENT_NAME_ID_FOR);
    samlPersistentNameId = user.getFirstAttribute(wildcardNameId);
    if (samlPersistentNameId != null) {
        return samlPersistentNameId;
    }
    // default to generated.  "G-" stands for "generated"
    samlPersistentNameId = "G-" + UUID.randomUUID().toString();
    user.setSingleAttribute(clientNameId, samlPersistentNameId);
    return samlPersistentNameId;
}
Also used : UserModel(org.keycloak.models.UserModel)

Example 45 with UserModel

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

the class UserAttributeMapper method setClaim.

protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession) {
    UserModel user = userSession.getUser();
    String attributeName = mappingModel.getConfig().get(ProtocolMapperUtils.USER_ATTRIBUTE);
    boolean aggregateAttrs = Boolean.valueOf(mappingModel.getConfig().get(ProtocolMapperUtils.AGGREGATE_ATTRS));
    Collection<String> attributeValue = KeycloakModelUtils.resolveAttribute(user, attributeName, aggregateAttrs);
    if (attributeValue == null)
        return;
    OIDCAttributeMapperHelper.mapClaim(token, mappingModel, attributeValue);
}
Also used : UserModel(org.keycloak.models.UserModel)

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