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;
}
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;
}
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;
}
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);
}
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();
}
Aggregations