use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ClientScopePolicyProviderFactory method postInit.
@Override
public void postInit(KeycloakSessionFactory factory) {
factory.register(event -> {
if (event instanceof ClientScopeRemovedEvent) {
KeycloakSession keycloakSession = ((ClientScopeRemovedEvent) event).getKeycloakSession();
AuthorizationProvider provider = keycloakSession.getProvider(AuthorizationProvider.class);
StoreFactory storeFactory = provider.getStoreFactory();
PolicyStore policyStore = storeFactory.getPolicyStore();
ClientScopeModel removedClientScope = ((ClientScopeRemovedEvent) event).getClientScope();
Map<Policy.FilterOption, String[]> filters = new HashMap<>();
filters.put(Policy.FilterOption.TYPE, new String[] { getId() });
policyStore.findByResourceServer(filters, null, -1, -1).forEach(new Consumer<Policy>() {
@Override
public void accept(Policy policy) {
List<Map<String, Object>> clientScopes = new ArrayList<>();
for (Map<String, Object> clientScope : getClientScopes(policy)) {
if (!clientScope.get("id").equals(removedClientScope.getId())) {
Map<String, Object> updated = new HashMap<>();
updated.put("id", clientScope.get("id"));
Object required = clientScope.get("required");
if (required != null) {
updated.put("required", required);
}
clientScopes.add(updated);
}
}
if (clientScopes.isEmpty()) {
policyStore.delete(policy.getId());
} else {
try {
policy.putConfig("clientScopes", JsonSerialization.writeValueAsString(clientScopes));
} catch (IOException e) {
throw new RuntimeException("Error while synchronizing client scopes with policy [" + policy.getName() + "].", e);
}
}
}
});
}
});
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ClientScopePolicyProvider method evaluate.
@Override
public void evaluate(Evaluation evaluation) {
Policy policy = evaluation.getPolicy();
Set<ClientScopePolicyRepresentation.ClientScopeDefinition> clientScopeIds = representationFunction.apply(policy, evaluation.getAuthorizationProvider()).getClientScopes();
AuthorizationProvider authorizationProvider = evaluation.getAuthorizationProvider();
RealmModel realm = authorizationProvider.getKeycloakSession().getContext().getRealm();
Identity identity = evaluation.getContext().getIdentity();
for (ClientScopePolicyRepresentation.ClientScopeDefinition clientScopeDefinition : clientScopeIds) {
ClientScopeModel clientScope = realm.getClientScopeById(clientScopeDefinition.getId());
if (clientScope != null) {
boolean hasClientScope = hasClientScope(identity, clientScope);
if (!hasClientScope && clientScopeDefinition.isRequired()) {
evaluation.deny();
return;
} else if (hasClientScope) {
evaluation.grant();
}
}
}
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ExportUtils method exportRealm.
public static RealmRepresentation exportRealm(KeycloakSession session, RealmModel realm, ExportOptions options, boolean internal) {
RealmRepresentation rep = ModelToRepresentation.toRepresentation(session, realm, internal);
ModelToRepresentation.exportAuthenticationFlows(realm, rep);
ModelToRepresentation.exportRequiredActions(realm, rep);
// Project/product version
rep.setKeycloakVersion(Version.VERSION_KEYCLOAK);
// Client Scopes
rep.setClientScopes(realm.getClientScopesStream().map(ModelToRepresentation::toRepresentation).collect(Collectors.toList()));
rep.setDefaultDefaultClientScopes(realm.getDefaultClientScopesStream(true).map(ClientScopeModel::getName).collect(Collectors.toList()));
rep.setDefaultOptionalClientScopes(realm.getDefaultClientScopesStream(false).map(ClientScopeModel::getName).collect(Collectors.toList()));
// Clients
List<ClientModel> clients = new LinkedList<>();
if (options.isClientsIncluded()) {
// we iterate over all clients in the stream.
// only those client models that can be translated into a valid client representation will be added to the client list
// that is later used to retrieve related information about groups and roles
List<ClientRepresentation> clientReps = ModelToRepresentation.filterValidRepresentations(realm.getClientsStream(), app -> {
ClientRepresentation clientRepresentation = exportClient(session, app);
clients.add(app);
return clientRepresentation;
}).collect(Collectors.toList());
rep.setClients(clientReps);
}
// Groups and Roles
if (options.isGroupsAndRolesIncluded()) {
ModelToRepresentation.exportGroups(realm, rep);
Map<String, List<RoleRepresentation>> clientRolesReps = new HashMap<>();
List<RoleRepresentation> realmRoleReps = exportRoles(realm.getRolesStream());
RolesRepresentation rolesRep = new RolesRepresentation();
if (!realmRoleReps.isEmpty()) {
rolesRep.setRealm(realmRoleReps);
}
if (options.isClientsIncluded()) {
for (ClientModel client : clients) {
Stream<RoleModel> currentAppRoles = client.getRolesStream();
List<RoleRepresentation> currentAppRoleReps = exportRoles(currentAppRoles);
clientRolesReps.put(client.getClientId(), currentAppRoleReps);
}
if (clientRolesReps.size() > 0) {
rolesRep.setClient(clientRolesReps);
}
}
rep.setRoles(rolesRep);
}
// Scopes
Map<String, List<ScopeMappingRepresentation>> clientScopeReps = new HashMap<>();
if (options.isClientsIncluded()) {
List<ClientModel> allClients = new ArrayList<>(clients);
// Scopes of clients
for (ClientModel client : allClients) {
Set<RoleModel> clientScopes = client.getScopeMappingsStream().collect(Collectors.toSet());
ScopeMappingRepresentation scopeMappingRep = null;
for (RoleModel scope : clientScopes) {
if (scope.getContainer() instanceof RealmModel) {
if (scopeMappingRep == null) {
scopeMappingRep = rep.clientScopeMapping(client.getClientId());
}
scopeMappingRep.role(scope.getName());
} else {
ClientModel app = (ClientModel) scope.getContainer();
String appName = app.getClientId();
List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
if (currentAppScopes == null) {
currentAppScopes = new ArrayList<>();
clientScopeReps.put(appName, currentAppScopes);
}
ScopeMappingRepresentation currentClientScope = null;
for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
if (client.getClientId().equals(scopeMapping.getClient())) {
currentClientScope = scopeMapping;
break;
}
}
if (currentClientScope == null) {
currentClientScope = new ScopeMappingRepresentation();
currentClientScope.setClient(client.getClientId());
currentAppScopes.add(currentClientScope);
}
currentClientScope.role(scope.getName());
}
}
}
}
// Scopes of client scopes
realm.getClientScopesStream().forEach(clientScope -> {
Set<RoleModel> clientScopes = clientScope.getScopeMappingsStream().collect(Collectors.toSet());
ScopeMappingRepresentation scopeMappingRep = null;
for (RoleModel scope : clientScopes) {
if (scope.getContainer() instanceof RealmModel) {
if (scopeMappingRep == null) {
scopeMappingRep = rep.clientScopeScopeMapping(clientScope.getName());
}
scopeMappingRep.role(scope.getName());
} else {
ClientModel app = (ClientModel) scope.getContainer();
String appName = app.getClientId();
List<ScopeMappingRepresentation> currentAppScopes = clientScopeReps.get(appName);
if (currentAppScopes == null) {
currentAppScopes = new ArrayList<>();
clientScopeReps.put(appName, currentAppScopes);
}
ScopeMappingRepresentation currentClientTemplateScope = null;
for (ScopeMappingRepresentation scopeMapping : currentAppScopes) {
if (clientScope.getName().equals(scopeMapping.getClientScope())) {
currentClientTemplateScope = scopeMapping;
break;
}
}
if (currentClientTemplateScope == null) {
currentClientTemplateScope = new ScopeMappingRepresentation();
currentClientTemplateScope.setClientScope(clientScope.getName());
currentAppScopes.add(currentClientTemplateScope);
}
currentClientTemplateScope.role(scope.getName());
}
}
});
if (clientScopeReps.size() > 0) {
rep.setClientScopeMappings(clientScopeReps);
}
// Finally users if needed
if (options.isUsersIncluded()) {
List<UserRepresentation> users = session.users().getUsersStream(realm, true).map(user -> exportUser(session, realm, user, options, internal)).collect(Collectors.toList());
if (users.size() > 0) {
rep.setUsers(users);
}
List<UserRepresentation> federatedUsers = session.userFederatedStorage().getStoredUsersStream(realm, 0, -1).map(user -> exportFederatedUser(session, realm, user, options)).collect(Collectors.toList());
if (federatedUsers.size() > 0) {
rep.setFederatedUsers(federatedUsers);
}
} else if (options.isClientsIncluded() && options.isOnlyServiceAccountsIncluded()) {
List<UserRepresentation> users = new LinkedList<>();
for (ClientModel app : clients) {
if (app.isServiceAccountsEnabled() && !app.isPublicClient() && !app.isBearerOnly()) {
UserModel user = session.users().getServiceAccount(app);
if (user != null) {
UserRepresentation userRep = exportUser(session, realm, user, options, internal);
users.add(userRep);
}
}
}
if (users.size() > 0) {
rep.setUsers(users);
}
}
// components
MultivaluedHashMap<String, ComponentExportRepresentation> components = exportComponents(realm, realm.getId());
rep.setComponents(components);
return rep;
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ClientScopesResource method createClientScope.
/**
* Create a new client scope
*
* Client Scope's name must be unique!
*
* @param rep
* @return
*/
@POST
@Consumes(MediaType.APPLICATION_JSON)
@NoCache
public Response createClientScope(ClientScopeRepresentation rep) {
auth.clients().requireManageClientScopes();
ClientScopeResource.validateDynamicClientScope(rep);
try {
ClientScopeModel clientModel = RepresentationToModel.createClientScope(session, realm, rep);
adminEvent.operation(OperationType.CREATE).resourcePath(session.getContext().getUri(), clientModel.getId()).representation(rep).success();
return Response.created(session.getContext().getUri().getAbsolutePathBuilder().path(clientModel.getId()).build()).build();
} catch (ModelDuplicateException e) {
return ErrorResponse.exists("Client Scope " + rep.getName() + " already exists");
}
}
use of org.keycloak.models.ClientScopeModel in project keycloak by keycloak.
the class ClientResource method addDefaultClientScope.
private void addDefaultClientScope(String clientScopeId, boolean defaultScope) {
auth.clients().requireManage(client);
ClientScopeModel clientScope = realm.getClientScopeById(clientScopeId);
if (clientScope == null) {
throw new javax.ws.rs.NotFoundException("Client scope not found");
}
if (defaultScope && clientScope.isDynamicScope()) {
throw new ErrorResponseException("invalid_request", "Can't assign a Dynamic Scope to a Client as a Default Scope", Response.Status.BAD_REQUEST);
}
client.addClientScope(clientScope, defaultScope);
adminEvent.operation(OperationType.CREATE).resource(ResourceType.CLIENT_SCOPE_CLIENT_MAPPING).resourcePath(session.getContext().getUri()).success();
}
Aggregations