Search in sources :

Example 21 with Scope

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());
}
Also used : ResourceServer(org.keycloak.authorization.model.ResourceServer) Scope(org.keycloak.authorization.model.Scope) Permission(org.keycloak.representations.idm.authorization.Permission) Set(java.util.Set) HashMap(java.util.HashMap) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) PermissionRequest(org.keycloak.representations.idm.authorization.PermissionRequest) ArrayList(java.util.ArrayList) List(java.util.List) Response(javax.ws.rs.core.Response) ErrorResponseException(org.keycloak.services.ErrorResponseException) Map(java.util.Map) Urls(org.keycloak.services.Urls) PermissionTicketToken(org.keycloak.representations.idm.authorization.PermissionTicketToken) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Collections(java.util.Collections) Resource(org.keycloak.authorization.model.Resource) PermissionResponse(org.keycloak.representations.idm.authorization.PermissionResponse) Scope(org.keycloak.authorization.model.Scope) ResourceStore(org.keycloak.authorization.store.ResourceStore) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 22 with Scope

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);
}
Also used : PermissionTicket(org.keycloak.authorization.model.PermissionTicket) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RealmsResource(org.keycloak.services.resources.RealmsResource) Resource(org.keycloak.authorization.model.Resource) UserModel(org.keycloak.models.UserModel) Scope(org.keycloak.authorization.model.Scope) PermissionTicketStore(org.keycloak.authorization.store.PermissionTicketStore) List(java.util.List) ArrayList(java.util.ArrayList) ResourceServer(org.keycloak.authorization.model.ResourceServer) EnumMap(java.util.EnumMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 23 with Scope

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) {
    }
}
Also used : Policy(org.keycloak.authorization.model.Policy) PermissionEvaluator(org.keycloak.authorization.permission.evaluator.PermissionEvaluator) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Resource(org.keycloak.authorization.model.Resource) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) ResourceServer(org.keycloak.authorization.model.ResourceServer) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 24 with Scope

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);
}
Also used : RealmModel(org.keycloak.models.RealmModel) Policy(org.keycloak.authorization.model.Policy) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) Scope(org.keycloak.authorization.model.Scope) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) RealmResource(org.keycloak.admin.client.resource.RealmResource) Resource(org.keycloak.authorization.model.Resource) AuthorizationProviderFactory(org.keycloak.authorization.AuthorizationProviderFactory) RoleModel(org.keycloak.models.RoleModel) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 25 with Scope

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;
}
Also used : Policy(org.keycloak.authorization.model.Policy) RolePolicyRepresentation(org.keycloak.representations.idm.authorization.RolePolicyRepresentation) ClientPolicyRepresentation(org.keycloak.representations.idm.authorization.ClientPolicyRepresentation) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) RoleDefinition(org.keycloak.representations.idm.authorization.RolePolicyRepresentation.RoleDefinition) RoleModel(org.keycloak.models.RoleModel) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) GroupPolicyRepresentation(org.keycloak.representations.idm.authorization.GroupPolicyRepresentation) AbstractPolicyRepresentation(org.keycloak.representations.idm.authorization.AbstractPolicyRepresentation) RealmModel(org.keycloak.models.RealmModel) Scope(org.keycloak.authorization.model.Scope) GroupDefinition(org.keycloak.representations.idm.authorization.GroupPolicyRepresentation.GroupDefinition) UserPolicyRepresentation(org.keycloak.representations.idm.authorization.UserPolicyRepresentation)

Aggregations

Scope (org.keycloak.authorization.model.Scope)65 Resource (org.keycloak.authorization.model.Resource)43 ResourceServer (org.keycloak.authorization.model.ResourceServer)39 Policy (org.keycloak.authorization.model.Policy)38 StoreFactory (org.keycloak.authorization.store.StoreFactory)21 HashSet (java.util.HashSet)19 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)19 ArrayList (java.util.ArrayList)18 List (java.util.List)17 ClientModel (org.keycloak.models.ClientModel)17 Map (java.util.Map)16 EnumMap (java.util.EnumMap)14 Collectors (java.util.stream.Collectors)14 PolicyStore (org.keycloak.authorization.store.PolicyStore)14 Collection (java.util.Collection)13 Set (java.util.Set)13 UserModel (org.keycloak.models.UserModel)13 Produces (javax.ws.rs.Produces)12 ResourceStore (org.keycloak.authorization.store.ResourceStore)12 KeycloakSession (org.keycloak.models.KeycloakSession)12