Search in sources :

Example 16 with AuthenticatorConfigModel

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

the class AuthenticationManagementResource method newExecutionConfig.

/**
 * Update execution with new configuration
 *
 * @param execution Execution id
 * @param json JSON with new configuration
 * @return
 */
@Path("/executions/{executionId}/config")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
public Response newExecutionConfig(@PathParam("executionId") String execution, AuthenticatorConfigRepresentation json) {
    auth.realm().requireManageRealm();
    ReservedCharValidator.validate(json.getAlias());
    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(execution);
    if (model == null) {
        session.getTransactionManager().setRollbackOnly();
        throw new NotFoundException("Illegal execution");
    }
    AuthenticatorConfigModel config = RepresentationToModel.toModel(json);
    if (config.getAlias() == null) {
        return ErrorResponse.error("Alias missing", Response.Status.BAD_REQUEST);
    }
    config = realm.addAuthenticatorConfig(config);
    model.setAuthenticatorConfig(config.getId());
    realm.updateAuthenticatorExecution(model);
    json.setId(config.getId());
    adminEvent.operation(OperationType.CREATE).resource(ResourceType.AUTH_EXECUTION).resourcePath(session.getContext().getUri()).representation(json).success();
    return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(config.getId()).build()).build();
}
Also used : AuthenticationExecutionModel(org.keycloak.models.AuthenticationExecutionModel) NotFoundException(javax.ws.rs.NotFoundException) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 17 with AuthenticatorConfigModel

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

the class AuthenticationManagementResource method removeAuthenticatorConfig.

/**
 * Delete authenticator configuration
 * @param id Configuration id
 */
@Path("config/{id}")
@DELETE
@NoCache
public void removeAuthenticatorConfig(@PathParam("id") String id) {
    auth.realm().requireManageRealm();
    AuthenticatorConfigModel config = realm.getAuthenticatorConfigById(id);
    if (config == null) {
        throw new NotFoundException("Could not find authenticator config");
    }
    realm.getAuthenticationFlowsStream().forEach(flow -> realm.getAuthenticationExecutionsStream(flow.getId()).filter(exe -> Objects.equals(id, exe.getAuthenticatorConfig())).forEachOrdered(exe -> {
        exe.setAuthenticatorConfig(null);
        realm.updateAuthenticatorExecution(exe);
    }));
    realm.removeAuthenticatorConfig(config);
    adminEvent.operation(OperationType.DELETE).resource(ResourceType.AUTHENTICATOR_CONFIG).resourcePath(session.getContext().getUri()).success();
}
Also used : ConfigPropertyRepresentation(org.keycloak.representations.idm.ConfigPropertyRepresentation) ResourceType(org.keycloak.events.admin.ResourceType) Produces(javax.ws.rs.Produces) RequiredActionFactory(org.keycloak.authentication.RequiredActionFactory) Path(javax.ws.rs.Path) ClientAuthenticatorFactory(org.keycloak.authentication.ClientAuthenticatorFactory) DefaultAuthenticationFlows(org.keycloak.models.utils.DefaultAuthenticationFlows) RepresentationToModel(org.keycloak.models.utils.RepresentationToModel) MediaType(javax.ws.rs.core.MediaType) Consumes(javax.ws.rs.Consumes) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) AuthenticationExecutionRepresentation(org.keycloak.representations.idm.AuthenticationExecutionRepresentation) FormAuthenticator(org.keycloak.authentication.FormAuthenticator) BadRequestException(javax.ws.rs.BadRequestException) UriBuilder(javax.ws.rs.core.UriBuilder) DELETE(javax.ws.rs.DELETE) RealmModel(org.keycloak.models.RealmModel) NOT_FOUND(javax.ws.rs.core.Response.Status.NOT_FOUND) CredentialHelper(org.keycloak.utils.CredentialHelper) Set(java.util.Set) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) ReservedCharValidator(org.keycloak.utils.ReservedCharValidator) Objects(java.util.Objects) ClientAuthenticator(org.keycloak.authentication.ClientAuthenticator) ModelToRepresentation(org.keycloak.models.utils.ModelToRepresentation) List(java.util.List) Stream(java.util.stream.Stream) Response(javax.ws.rs.core.Response) Optional(java.util.Optional) RequiredActionProviderModel(org.keycloak.models.RequiredActionProviderModel) OperationType(org.keycloak.events.admin.OperationType) PathParam(javax.ws.rs.PathParam) AuthenticationFlow(org.keycloak.authentication.AuthenticationFlow) AuthenticatorConfigInfoRepresentation(org.keycloak.representations.idm.AuthenticatorConfigInfoRepresentation) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) HashMap(java.util.HashMap) AuthenticationExecutionInfoRepresentation(org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation) AuthenticationExecutionModel(org.keycloak.models.AuthenticationExecutionModel) AuthenticationFlowRepresentation(org.keycloak.representations.idm.AuthenticationFlowRepresentation) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) AuthenticationFlowModel(org.keycloak.models.AuthenticationFlowModel) ConfigurableAuthenticatorFactory(org.keycloak.authentication.ConfigurableAuthenticatorFactory) LinkedList(java.util.LinkedList) ProviderFactory(org.keycloak.provider.ProviderFactory) FormAction(org.keycloak.authentication.FormAction) POST(javax.ws.rs.POST) Authenticator(org.keycloak.authentication.Authenticator) AdminPermissionEvaluator(org.keycloak.services.resources.admin.permissions.AdminPermissionEvaluator) KeycloakSession(org.keycloak.models.KeycloakSession) RequiredActionProviderRepresentation(org.keycloak.representations.idm.RequiredActionProviderRepresentation) RequiredActionProvider(org.keycloak.authentication.RequiredActionProvider) AuthenticatorConfigRepresentation(org.keycloak.representations.idm.AuthenticatorConfigRepresentation) NoCache(org.jboss.resteasy.annotations.cache.NoCache) PUT(javax.ws.rs.PUT) Collections(java.util.Collections) ErrorResponse(org.keycloak.services.ErrorResponse) NotFoundException(javax.ws.rs.NotFoundException) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 18 with AuthenticatorConfigModel

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

the class AuthenticationManagementResource method createAuthenticatorConfig.

/**
 * Create new authenticator configuration
 * @param rep JSON describing new authenticator configuration
 * @deprecated Use {@link #newExecutionConfig(String, AuthenticatorConfigRepresentation)} instead
 */
@Path("config")
@POST
@NoCache
@Consumes(MediaType.APPLICATION_JSON)
public Response createAuthenticatorConfig(AuthenticatorConfigRepresentation rep) {
    auth.realm().requireManageRealm();
    ReservedCharValidator.validate(rep.getAlias());
    AuthenticatorConfigModel config = realm.addAuthenticatorConfig(RepresentationToModel.toModel(rep));
    adminEvent.operation(OperationType.CREATE).resource(ResourceType.AUTHENTICATOR_CONFIG).resourcePath(session.getContext().getUri(), config.getId()).representation(rep).success();
    return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(config.getId()).build()).build();
}
Also used : AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 19 with AuthenticatorConfigModel

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

the class IdpCreateUserIfUniqueAuthenticator method authenticateImpl.

@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);
        for (Map.Entry<String, List<String>> attr : serializedCtx.getAttributes().entrySet()) {
            if (!UserModel.USERNAME.equalsIgnoreCase(attr.getKey())) {
                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();
        }
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) Response(javax.ws.rs.core.Response) ExistingUserInfo(org.keycloak.authentication.authenticators.broker.util.ExistingUserInfo) KeycloakSession(org.keycloak.models.KeycloakSession) List(java.util.List) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) Map(java.util.Map)

Example 20 with AuthenticatorConfigModel

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

the class DenyAccessAuthenticator method authenticate.

@Override
public void authenticate(AuthenticationFlowContext context) {
    String errorMessage = Optional.ofNullable(context.getAuthenticatorConfig()).map(AuthenticatorConfigModel::getConfig).map(f -> f.get(DenyAccessAuthenticatorFactory.ERROR_MESSAGE)).orElse(Messages.ACCESS_DENIED);
    context.getEvent().error(Errors.ACCESS_DENIED);
    Response challenge = context.form().setError(errorMessage).createErrorPage(Response.Status.UNAUTHORIZED);
    context.failure(AuthenticationFlowError.ACCESS_DENIED, challenge);
}
Also used : AuthenticationFlowError(org.keycloak.authentication.AuthenticationFlowError) Errors(org.keycloak.events.Errors) RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) Response(javax.ws.rs.core.Response) Authenticator(org.keycloak.authentication.Authenticator) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel) KeycloakSession(org.keycloak.models.KeycloakSession) Optional(java.util.Optional) AuthenticationFlowContext(org.keycloak.authentication.AuthenticationFlowContext) Messages(org.keycloak.services.messages.Messages) Response(javax.ws.rs.core.Response) AuthenticatorConfigModel(org.keycloak.models.AuthenticatorConfigModel)

Aggregations

AuthenticatorConfigModel (org.keycloak.models.AuthenticatorConfigModel)28 AuthenticationExecutionModel (org.keycloak.models.AuthenticationExecutionModel)13 AuthenticationFlowModel (org.keycloak.models.AuthenticationFlowModel)9 RealmModel (org.keycloak.models.RealmModel)9 HashMap (java.util.HashMap)6 NotFoundException (javax.ws.rs.NotFoundException)5 Path (javax.ws.rs.Path)5 NoCache (org.jboss.resteasy.annotations.cache.NoCache)5 List (java.util.List)4 Consumes (javax.ws.rs.Consumes)4 Response (javax.ws.rs.core.Response)4 KeycloakSession (org.keycloak.models.KeycloakSession)4 UserModel (org.keycloak.models.UserModel)4 Map (java.util.Map)3 Optional (java.util.Optional)3 POST (javax.ws.rs.POST)3 Before (org.junit.Before)3 Authenticator (org.keycloak.authentication.Authenticator)3 Collections (java.util.Collections)2 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2