use of org.keycloak.authorization.model.Scope in project keycloak by keycloak.
the class AbstractPermissionService method verifyRequestedScopes.
private Set<String> verifyRequestedScopes(PermissionRequest request, Resource resource) {
Set<String> requestScopes = request.getScopes();
if (requestScopes == null) {
return Collections.emptySet();
}
ResourceStore resourceStore = authorization.getStoreFactory().getResourceStore();
return requestScopes.stream().map(scopeName -> {
Scope scope = null;
if (resource != null) {
scope = resource.getScopes().stream().filter(scope1 -> scope1.getName().equals(scopeName)).findFirst().orElse(null);
if (scope == null && resource.getType() != null) {
scope = resourceStore.findByType(resource.getType(), resourceServer.getId()).stream().filter(baseResource -> baseResource.getOwner().equals(resource.getResourceServer())).flatMap(resource1 -> resource1.getScopes().stream()).filter(baseScope -> baseScope.getName().equals(scopeName)).findFirst().orElse(null);
}
} else {
scope = authorization.getStoreFactory().getScopeStore().findByName(scopeName, resourceServer.getId());
}
if (scope == null) {
throw new ErrorResponseException("invalid_scope", "Scope [" + scopeName + "] is invalid", Response.Status.BAD_REQUEST);
}
return scope.getName();
}).collect(Collectors.toSet());
}
use of org.keycloak.authorization.model.Scope in project keycloak by keycloak.
the class AccountFormService method shareResource.
@Path("resource/{resource_id}/share")
@POST
public Response shareResource(@PathParam("resource_id") String resourceId, @FormParam("user_id") String[] userIds, @FormParam("scope_id") String[] scopes) {
MultivaluedMap<String, String> formData = request.getDecodedFormParameters();
if (auth == null) {
return login("resource");
}
auth.require(AccountRoles.MANAGE_ACCOUNT);
csrfCheck(formData);
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
PermissionTicketStore ticketStore = authorization.getStoreFactory().getPermissionTicketStore();
Resource resource = authorization.getStoreFactory().getResourceStore().findById(resourceId, null);
ResourceServer resourceServer = authorization.getStoreFactory().getResourceServerStore().findById(resource.getResourceServer());
if (resource == null) {
return ErrorResponse.error("Invalid resource", Response.Status.BAD_REQUEST);
}
if (userIds == null || userIds.length == 0) {
setReferrerOnPage();
return account.setError(Status.BAD_REQUEST, Messages.MISSING_PASSWORD).createResponse(AccountPages.PASSWORD);
}
for (String id : userIds) {
UserModel user = session.users().getUserById(realm, id);
if (user == null) {
user = session.users().getUserByUsername(realm, id);
}
if (user == null) {
user = session.users().getUserByEmail(realm, id);
}
if (user == null) {
setReferrerOnPage();
return account.setError(Status.BAD_REQUEST, Messages.INVALID_USER).createResponse(AccountPages.RESOURCE_DETAIL);
}
Map<PermissionTicket.FilterOption, String> filters = new EnumMap<>(PermissionTicket.FilterOption.class);
filters.put(PermissionTicket.FilterOption.RESOURCE_ID, resource.getId());
filters.put(PermissionTicket.FilterOption.OWNER, auth.getUser().getId());
filters.put(PermissionTicket.FilterOption.REQUESTER, user.getId());
List<PermissionTicket> tickets = ticketStore.find(filters, resource.getResourceServer(), -1, -1);
if (tickets.isEmpty()) {
if (scopes != null && scopes.length > 0) {
for (String scope : scopes) {
PermissionTicket ticket = ticketStore.create(resourceId, scope, user.getId(), resourceServer);
ticket.setGrantedTimestamp(System.currentTimeMillis());
}
} else {
if (resource.getScopes().isEmpty()) {
PermissionTicket ticket = ticketStore.create(resourceId, null, user.getId(), resourceServer);
ticket.setGrantedTimestamp(System.currentTimeMillis());
} else {
for (Scope scope : resource.getScopes()) {
PermissionTicket ticket = ticketStore.create(resourceId, scope.getId(), user.getId(), resourceServer);
ticket.setGrantedTimestamp(System.currentTimeMillis());
}
}
}
} else if (scopes != null && scopes.length > 0) {
List<String> grantScopes = new ArrayList<>(Arrays.asList(scopes));
for (PermissionTicket ticket : tickets) {
Scope scope = ticket.getScope();
if (scope != null) {
grantScopes.remove(scope.getId());
}
}
for (String grantScope : grantScopes) {
PermissionTicket ticket = ticketStore.create(resourceId, grantScope, user.getId(), resourceServer);
ticket.setGrantedTimestamp(System.currentTimeMillis());
}
}
}
return forwardToPage("resource", AccountPages.RESOURCE_DETAIL);
}
use of org.keycloak.authorization.model.Scope in project keycloak by keycloak.
the class PolicyEvaluationTest method testCheckReadOnlyInstances.
public static void testCheckReadOnlyInstances(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealmByName("authz-test"));
AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
ClientModel clientModel = session.clients().getClientByClientId(session.getContext().getRealm(), "resource-server-test");
StoreFactory storeFactory = authorization.getStoreFactory();
ResourceServer resourceServer = storeFactory.getResourceServerStore().findByClient(clientModel);
JSPolicyRepresentation policyRepresentation = new JSPolicyRepresentation();
policyRepresentation.setName("testCheckReadOnlyInstances");
StringBuilder builder = new StringBuilder();
builder.append("$evaluation.getPermission().getResource().setName('test')");
policyRepresentation.setCode(builder.toString());
Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
Resource resource = storeFactory.getResourceStore().create("Resource A", resourceServer, resourceServer.getId());
Scope scope = storeFactory.getScopeStore().create("Scope A", resourceServer);
resource.updateScopes(new HashSet<>(Arrays.asList(scope)));
ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
permission.setName("testCheckReadOnlyInstances permission");
permission.addPolicy(policy.getId());
permission.addResource(resource.getId());
storeFactory.getPolicyStore().create(permission, resourceServer);
session.getTransactionManager().commit();
PermissionEvaluator evaluator = authorization.evaluators().from(Arrays.asList(new ResourcePermission(resource, Arrays.asList(scope), resourceServer)), createEvaluationContext(session, Collections.emptyMap()));
try {
evaluator.evaluate(resourceServer, null);
Assert.fail("Instances should be marked as read-only");
} catch (Exception ignore) {
}
}
use of org.keycloak.authorization.model.Scope in project keycloak by keycloak.
the class PolicyEvaluationCompositeRoleTest method setup.
public static void setup(KeycloakSession session) {
RealmModel realm = session.realms().getRealmByName(TEST);
session.getContext().setRealm(realm);
ClientModel client = session.clients().addClient(realm, "myclient");
RoleModel role1 = client.addRole("client-role1");
AuthorizationProviderFactory factory = (AuthorizationProviderFactory) session.getKeycloakSessionFactory().getProviderFactory(AuthorizationProvider.class);
AuthorizationProvider authz = factory.create(session, realm);
ResourceServer resourceServer = authz.getStoreFactory().getResourceServerStore().create(client);
Policy policy = createRolePolicy(authz, resourceServer, role1);
Scope scope = authz.getStoreFactory().getScopeStore().create("myscope", resourceServer);
Resource resource = authz.getStoreFactory().getResourceStore().create("myresource", resourceServer, resourceServer.getId());
addScopePermission(authz, resourceServer, "mypermission", resource, scope, policy);
RoleModel composite = realm.addRole("composite");
composite.addCompositeRole(role1);
UserModel user = session.users().addUser(realm, "user");
user.grantRole(composite);
}
use of org.keycloak.authorization.model.Scope in project keycloak by keycloak.
the class UMAPolicyProviderFactory method toRepresentation.
@Override
public UmaPermissionRepresentation toRepresentation(Policy policy, AuthorizationProvider authorization) {
UmaPermissionRepresentation representation = new UmaPermissionRepresentation();
representation.setScopes(policy.getScopes().stream().map(Scope::getName).collect(Collectors.toSet()));
representation.setOwner(policy.getOwner());
for (Policy associatedPolicy : policy.getAssociatedPolicies()) {
AbstractPolicyRepresentation associatedRep = ModelToRepresentation.toRepresentation(associatedPolicy, authorization, false, false);
RealmModel realm = authorization.getRealm();
if ("role".equals(associatedRep.getType())) {
RolePolicyRepresentation rep = RolePolicyRepresentation.class.cast(associatedRep);
for (RoleDefinition definition : rep.getRoles()) {
RoleModel role = realm.getRoleById(definition.getId());
if (role.isClientRole()) {
representation.addClientRole(ClientModel.class.cast(role.getContainer()).getClientId(), role.getName());
} else {
representation.addRole(role.getName());
}
}
} else if ("js".equals(associatedRep.getType())) {
JSPolicyRepresentation rep = JSPolicyRepresentation.class.cast(associatedRep);
representation.setCondition(rep.getCode());
} else if ("group".equals(associatedRep.getType())) {
GroupPolicyRepresentation rep = GroupPolicyRepresentation.class.cast(associatedRep);
for (GroupDefinition definition : rep.getGroups()) {
representation.addGroup(ModelToRepresentation.buildGroupPath(realm.getGroupById(definition.getId())));
}
} else if ("client".equals(associatedRep.getType())) {
ClientPolicyRepresentation rep = ClientPolicyRepresentation.class.cast(associatedRep);
for (String client : rep.getClients()) {
representation.addClient(realm.getClientById(client).getClientId());
}
} else if ("user".equals(associatedPolicy.getType())) {
UserPolicyRepresentation rep = UserPolicyRepresentation.class.cast(associatedRep);
for (String user : rep.getUsers()) {
representation.addUser(authorization.getKeycloakSession().users().getUserById(realm, user).getUsername());
}
}
}
return representation;
}
Aggregations