Search in sources :

Example 1 with IdentityProviderMapperModel

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

the class DefaultTokenExchangeProvider method importUserFromExternalIdentity.

protected UserModel importUserFromExternalIdentity(BrokeredIdentityContext context) {
    IdentityProviderModel identityProviderConfig = context.getIdpConfig();
    String providerId = identityProviderConfig.getAlias();
    // do we need this?
    // AuthenticationSessionModel authenticationSession = clientCode.getClientSession();
    // context.setAuthenticationSession(authenticationSession);
    // session.getContext().setClient(authenticationSession.getClient());
    context.getIdp().preprocessFederatedIdentity(session, realm, context);
    Set<IdentityProviderMapperModel> mappers = realm.getIdentityProviderMappersByAliasStream(context.getIdpConfig().getAlias()).collect(Collectors.toSet());
    KeycloakSessionFactory sessionFactory = session.getKeycloakSessionFactory();
    for (IdentityProviderMapperModel mapper : mappers) {
        IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
        target.preprocessFederatedIdentity(session, realm, mapper, context);
    }
    FederatedIdentityModel federatedIdentityModel = new FederatedIdentityModel(providerId, context.getId(), context.getUsername(), context.getToken());
    UserModel user = this.session.users().getUserByFederatedIdentity(realm, federatedIdentityModel);
    if (user == null) {
        logger.debugf("Federated user not found for provider '%s' and broker username '%s'.", providerId, context.getUsername());
        String username = context.getModelUsername();
        if (username == null) {
            if (this.realm.isRegistrationEmailAsUsername() && !Validation.isBlank(context.getEmail())) {
                username = context.getEmail();
            } else if (context.getUsername() == null) {
                username = context.getIdpConfig().getAlias() + "." + context.getId();
            } else {
                username = context.getUsername();
            }
        }
        username = username.trim();
        context.setModelUsername(username);
        if (context.getEmail() != null && !realm.isDuplicateEmailsAllowed()) {
            UserModel existingUser = session.users().getUserByEmail(realm, context.getEmail());
            if (existingUser != null) {
                event.error(Errors.FEDERATED_IDENTITY_EXISTS);
                throw new CorsErrorResponseException(cors, Errors.INVALID_TOKEN, "User already exists", Response.Status.BAD_REQUEST);
            }
        }
        UserModel existingUser = session.users().getUserByUsername(realm, username);
        if (existingUser != null) {
            event.error(Errors.FEDERATED_IDENTITY_EXISTS);
            throw new CorsErrorResponseException(cors, Errors.INVALID_TOKEN, "User already exists", Response.Status.BAD_REQUEST);
        }
        user = session.users().addUser(realm, username);
        user.setEnabled(true);
        user.setEmail(context.getEmail());
        user.setFirstName(context.getFirstName());
        user.setLastName(context.getLastName());
        federatedIdentityModel = new FederatedIdentityModel(context.getIdpConfig().getAlias(), context.getId(), context.getUsername(), context.getToken());
        session.users().addFederatedIdentity(realm, user, federatedIdentityModel);
        context.getIdp().importNewUser(session, realm, user, context);
        for (IdentityProviderMapperModel mapper : mappers) {
            IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
            target.importNewUser(session, realm, user, mapper, context);
        }
        if (context.getIdpConfig().isTrustEmail() && !Validation.isBlank(user.getEmail())) {
            logger.debugf("Email verified automatically after registration of user '%s' through Identity provider '%s' ", user.getUsername(), context.getIdpConfig().getAlias());
            user.setEmailVerified(true);
        }
    } else {
        if (!user.isEnabled()) {
            event.error(Errors.USER_DISABLED);
            throw new CorsErrorResponseException(cors, Errors.INVALID_TOKEN, "Invalid Token", Response.Status.BAD_REQUEST);
        }
        String bruteForceError = getDisabledByBruteForceEventError(session.getProvider(BruteForceProtector.class), session, realm, user);
        if (bruteForceError != null) {
            event.error(bruteForceError);
            throw new CorsErrorResponseException(cors, Errors.INVALID_TOKEN, "Invalid Token", Response.Status.BAD_REQUEST);
        }
        context.getIdp().updateBrokeredUser(session, realm, user, context);
        for (IdentityProviderMapperModel mapper : mappers) {
            IdentityProviderMapper target = (IdentityProviderMapper) sessionFactory.getProviderFactory(IdentityProviderMapper.class, mapper.getIdentityProviderMapper());
            IdentityProviderMapperSyncModeDelegate.delegateUpdateBrokeredUser(session, realm, user, mapper, context, target);
        }
    }
    return user;
}
Also used : UserModel(org.keycloak.models.UserModel) IdentityProviderMapper(org.keycloak.broker.provider.IdentityProviderMapper) FederatedIdentityModel(org.keycloak.models.FederatedIdentityModel) BruteForceProtector(org.keycloak.services.managers.BruteForceProtector) IdentityProviderModel(org.keycloak.models.IdentityProviderModel) CorsErrorResponseException(org.keycloak.services.CorsErrorResponseException) KeycloakSessionFactory(org.keycloak.models.KeycloakSessionFactory) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel)

Example 2 with IdentityProviderMapperModel

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

the class MapIdentityProviderMapperEntity method toModel.

static IdentityProviderMapperModel toModel(MapIdentityProviderMapperEntity entity) {
    if (entity == null)
        return null;
    IdentityProviderMapperModel model = new IdentityProviderMapperModel();
    model.setId(entity.getId());
    model.setName(entity.getName());
    model.setIdentityProviderAlias(entity.getIdentityProviderAlias());
    model.setIdentityProviderMapper(entity.getIdentityProviderMapper());
    model.setConfig(entity.getConfig() == null ? null : new HashMap<>(entity.getConfig()));
    return model;
}
Also used : HashMap(java.util.HashMap) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel)

Example 3 with IdentityProviderMapperModel

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

the class AdvancedAttributeToRoleMapper method applies.

protected boolean applies(final IdentityProviderMapperModel mapperModel, final BrokeredIdentityContext context) {
    Map<String, String> attributes = mapperModel.getConfigMap(ATTRIBUTE_PROPERTY_NAME);
    boolean areAttributeValuesRegexes = Boolean.parseBoolean(mapperModel.getConfig().get(ARE_ATTRIBUTE_VALUES_REGEX_PROPERTY_NAME));
    AssertionType assertion = (AssertionType) context.getContextData().get(SAMLEndpoint.SAML_ASSERTION);
    Set<AttributeStatementType> attributeAssertions = assertion.getAttributeStatements();
    if (attributeAssertions == null) {
        return false;
    }
    for (Map.Entry<String, String> attribute : attributes.entrySet()) {
        String attributeKey = attribute.getKey();
        List<Object> attributeValues = attributeAssertions.stream().flatMap(statements -> statements.getAttributes().stream()).filter(choiceType -> attributeKey.equals(choiceType.getAttribute().getName()) || attributeKey.equals(choiceType.getAttribute().getFriendlyName())).flatMap(choiceType -> choiceType.getAttribute().getAttributeValue().stream()).collect(Collectors.toList());
        boolean attributeValueMatch = areAttributeValuesRegexes ? valueMatchesRegex(attribute.getValue(), attributeValues) : attributeValues.contains(attribute.getValue());
        if (!attributeValueMatch) {
            return false;
        }
    }
    return true;
}
Also used : RegexUtils.valueMatchesRegex(org.keycloak.utils.RegexUtils.valueMatchesRegex) Arrays(java.util.Arrays) SAMLEndpoint(org.keycloak.broker.saml.SAMLEndpoint) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) IdentityProviderSyncMode(org.keycloak.models.IdentityProviderSyncMode) ProviderConfigProperty(org.keycloak.provider.ProviderConfigProperty) Set(java.util.Set) BrokeredIdentityContext(org.keycloak.broker.provider.BrokeredIdentityContext) ConfigConstants(org.keycloak.broker.provider.ConfigConstants) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) HashSet(java.util.HashSet) List(java.util.List) SAMLIdentityProviderFactory(org.keycloak.broker.saml.SAMLIdentityProviderFactory) Map(java.util.Map) AttributeStatementType(org.keycloak.dom.saml.v2.assertion.AttributeStatementType) AssertionType(org.keycloak.dom.saml.v2.assertion.AssertionType) Map(java.util.Map)

Example 4 with IdentityProviderMapperModel

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

the class IdentityProviderResource method getMapperById.

/**
 * Get mapper by id for the identity provider
 *
 * @param id
 * @return
 */
@GET
@NoCache
@Path("mappers/{id}")
@Produces(MediaType.APPLICATION_JSON)
public IdentityProviderMapperRepresentation getMapperById(@PathParam("id") String id) {
    this.auth.realm().requireViewIdentityProviders();
    if (identityProviderModel == null) {
        throw new javax.ws.rs.NotFoundException();
    }
    IdentityProviderMapperModel model = realm.getIdentityProviderMapperById(id);
    if (model == null)
        throw new NotFoundException("Model not found");
    return ModelToRepresentation.toRepresentation(model);
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) NoCache(org.jboss.resteasy.annotations.cache.NoCache)

Example 5 with IdentityProviderMapperModel

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

the class IdentityProviderResource method addMapper.

/**
 * Add a mapper to identity provider
 *
 * @param mapper
 * @return
 */
@POST
@Path("mappers")
@Consumes(MediaType.APPLICATION_JSON)
public Response addMapper(IdentityProviderMapperRepresentation mapper) {
    this.auth.realm().requireManageIdentityProviders();
    if (identityProviderModel == null) {
        throw new javax.ws.rs.NotFoundException();
    }
    IdentityProviderMapperModel model = RepresentationToModel.toModel(mapper);
    try {
        model = realm.addIdentityProviderMapper(model);
    } catch (Exception e) {
        return ErrorResponse.error("Failed to add mapper '" + model.getName() + "' to identity provider [" + identityProviderModel.getProviderId() + "].", Response.Status.BAD_REQUEST);
    }
    adminEvent.operation(OperationType.CREATE).resource(ResourceType.IDENTITY_PROVIDER_MAPPER).resourcePath(session.getContext().getUri(), model.getId()).representation(mapper).success();
    return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(model.getId()).build()).build();
}
Also used : NotFoundException(javax.ws.rs.NotFoundException) IdentityProviderMapperModel(org.keycloak.models.IdentityProviderMapperModel) NotFoundException(javax.ws.rs.NotFoundException) ModelDuplicateException(org.keycloak.models.ModelDuplicateException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes)

Aggregations

IdentityProviderMapperModel (org.keycloak.models.IdentityProviderMapperModel)8 NotFoundException (javax.ws.rs.NotFoundException)4 Path (javax.ws.rs.Path)4 NoCache (org.jboss.resteasy.annotations.cache.NoCache)3 Consumes (javax.ws.rs.Consumes)2 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 Collectors (java.util.stream.Collectors)1 DELETE (javax.ws.rs.DELETE)1 GET (javax.ws.rs.GET)1 POST (javax.ws.rs.POST)1 PUT (javax.ws.rs.PUT)1 Produces (javax.ws.rs.Produces)1 BrokeredIdentityContext (org.keycloak.broker.provider.BrokeredIdentityContext)1 ConfigConstants (org.keycloak.broker.provider.ConfigConstants)1