Search in sources :

Example 31 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class AuthorizationTokenService method resolvePreviousGrantedPermissions.

private void resolvePreviousGrantedPermissions(PermissionTicketToken ticket, KeycloakAuthorizationRequest request, ResourceServer resourceServer, Map<String, ResourcePermission> permissionsToEvaluate, ResourceStore resourceStore, ScopeStore scopeStore, AtomicInteger limit) {
    AccessToken rpt = request.getRpt();
    if (rpt != null && rpt.isActive()) {
        Authorization authorizationData = rpt.getAuthorization();
        if (authorizationData != null) {
            Collection<Permission> permissions = authorizationData.getPermissions();
            if (permissions != null) {
                for (Permission grantedPermission : permissions) {
                    if (limit != null && limit.get() <= 0) {
                        break;
                    }
                    Resource resource = resourceStore.findById(grantedPermission.getResourceId(), ticket.getIssuedFor());
                    if (resource != null) {
                        ResourcePermission permission = permissionsToEvaluate.get(resource.getId());
                        if (permission == null) {
                            permission = new ResourcePermission(resource, new ArrayList<>(), resourceServer, grantedPermission.getClaims());
                            permissionsToEvaluate.put(resource.getId(), permission);
                            if (limit != null) {
                                limit.decrementAndGet();
                            }
                        } else {
                            if (grantedPermission.getClaims() != null) {
                                for (Entry<String, Set<String>> entry : grantedPermission.getClaims().entrySet()) {
                                    Set<String> claims = permission.getClaims().get(entry.getKey());
                                    if (claims != null) {
                                        claims.addAll(entry.getValue());
                                    }
                                }
                            }
                        }
                        for (String scopeName : grantedPermission.getScopes()) {
                            Scope scope = scopeStore.findByName(scopeName, resourceServer.getId());
                            if (scope != null) {
                                if (!permission.getScopes().contains(scope)) {
                                    permission.getScopes().add(scope);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) Set(java.util.Set) HashSet(java.util.HashSet) Scope(org.keycloak.authorization.model.Scope) AccessToken(org.keycloak.representations.AccessToken) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Permission(org.keycloak.representations.idm.authorization.Permission) Resource(org.keycloak.authorization.model.Resource) ArrayList(java.util.ArrayList) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission)

Example 32 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class UserManagedPermissionService method checkRequest.

private void checkRequest(String resourceId, UmaPermissionRepresentation representation) {
    ResourceStore resourceStore = this.authorization.getStoreFactory().getResourceStore();
    Resource resource = resourceStore.findById(resourceId, resourceServer.getId());
    if (resource == null) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Resource [" + resourceId + "] cannot be found", Response.Status.BAD_REQUEST);
    }
    if (!resource.getOwner().equals(identity.getId())) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resource owner can access policies for resource [" + resourceId + "]", Status.BAD_REQUEST);
    }
    if (!resource.isOwnerManagedAccess()) {
        throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Only resources with owner managed accessed can have policies", Status.BAD_REQUEST);
    }
    if (!resourceServer.isAllowRemoteResourceManagement()) {
        throw new ErrorResponseException(OAuthErrorException.REQUEST_NOT_SUPPORTED, "Remote Resource Management not enabled on resource server [" + resourceServer.getId() + "]", Status.FORBIDDEN);
    }
    if (representation != null) {
        Set<String> resourceScopes = resource.getScopes().stream().map(scope -> scope.getName()).collect(Collectors.toSet());
        Set<String> scopes = representation.getScopes();
        if (scopes == null || scopes.isEmpty()) {
            scopes = resourceScopes;
            representation.setScopes(scopes);
        }
        if (!resourceScopes.containsAll(scopes)) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Some of the scopes [" + scopes + "] are not valid for resource [" + resourceId + "]", Response.Status.BAD_REQUEST);
        }
        if (representation.getCondition() != null) {
            if (!Profile.isFeatureEnabled(Profile.Feature.UPLOAD_SCRIPTS)) {
                throw new ErrorResponseException(OAuthErrorException.INVALID_REQUEST, "Script upload not supported", Status.BAD_REQUEST);
            }
        }
    }
}
Also used : PathParam(javax.ws.rs.PathParam) Produces(javax.ws.rs.Produces) Profile(org.keycloak.common.Profile) GET(javax.ws.rs.GET) Path(javax.ws.rs.Path) ResteasyProviderFactory(org.jboss.resteasy.spi.ResteasyProviderFactory) OAuthErrorException(org.keycloak.OAuthErrorException) QueryParam(javax.ws.rs.QueryParam) Consumes(javax.ws.rs.Consumes) ErrorResponseException(org.keycloak.services.ErrorResponseException) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) Status(javax.ws.rs.core.Response.Status) Identity(org.keycloak.authorization.identity.Identity) DELETE(javax.ws.rs.DELETE) PolicyTypeResourceService(org.keycloak.authorization.admin.PolicyTypeResourceService) ResourceServer(org.keycloak.authorization.model.ResourceServer) POST(javax.ws.rs.POST) Set(java.util.Set) IOException(java.io.IOException) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) PermissionService(org.keycloak.authorization.admin.PermissionService) JsonSerialization(org.keycloak.util.JsonSerialization) Policy(org.keycloak.authorization.model.Policy) Response(javax.ws.rs.core.Response) NoCache(org.jboss.resteasy.annotations.cache.NoCache) UmaPermissionRepresentation(org.keycloak.representations.idm.authorization.UmaPermissionRepresentation) PUT(javax.ws.rs.PUT) Resource(org.keycloak.authorization.model.Resource) AdminEventBuilder(org.keycloak.services.resources.admin.AdminEventBuilder) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore) ErrorResponseException(org.keycloak.services.ErrorResponseException)

Example 33 with Resource

use of org.keycloak.authorization.model.Resource in project keycloak by keycloak.

the class ScopeService method delete.

@Path("{id}")
@DELETE
public Response delete(@PathParam("id") String id) {
    this.auth.realm().requireManageAuthorization();
    StoreFactory storeFactory = authorization.getStoreFactory();
    List<Resource> resources = storeFactory.getResourceStore().findByScope(Arrays.asList(id), resourceServer.getId());
    if (!resources.isEmpty()) {
        return ErrorResponse.error("Scopes can not be removed while associated with resources.", Status.BAD_REQUEST);
    }
    Scope scope = storeFactory.getScopeStore().findById(id, resourceServer.getId());
    if (scope == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    PolicyStore policyStore = storeFactory.getPolicyStore();
    List<Policy> policies = policyStore.findByScopeIds(Arrays.asList(scope.getId()), resourceServer.getId());
    for (Policy policyModel : policies) {
        if (policyModel.getScopes().size() == 1) {
            policyStore.delete(policyModel.getId());
        } else {
            policyModel.removeScope(scope);
        }
    }
    storeFactory.getScopeStore().delete(id);
    audit(toRepresentation(scope), OperationType.DELETE);
    return Response.noContent().build();
}
Also used : Policy(org.keycloak.authorization.model.Policy) Scope(org.keycloak.authorization.model.Scope) Resource(org.keycloak.authorization.model.Resource) PolicyStore(org.keycloak.authorization.store.PolicyStore) StoreFactory(org.keycloak.authorization.store.StoreFactory) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE)

Example 34 with Resource

use of org.keycloak.authorization.model.Resource 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 35 with Resource

use of org.keycloak.authorization.model.Resource 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)

Aggregations

Resource (org.keycloak.authorization.model.Resource)87 ResourceServer (org.keycloak.authorization.model.ResourceServer)51 Policy (org.keycloak.authorization.model.Policy)45 Scope (org.keycloak.authorization.model.Scope)44 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)27 ResourceStore (org.keycloak.authorization.store.ResourceStore)27 StoreFactory (org.keycloak.authorization.store.StoreFactory)26 ArrayList (java.util.ArrayList)22 ClientModel (org.keycloak.models.ClientModel)22 List (java.util.List)20 HashSet (java.util.HashSet)19 Map (java.util.Map)19 UserModel (org.keycloak.models.UserModel)18 RealmModel (org.keycloak.models.RealmModel)16 HashMap (java.util.HashMap)15 Set (java.util.Set)15 EnumMap (java.util.EnumMap)14 Collectors (java.util.stream.Collectors)14 Path (javax.ws.rs.Path)13 PolicyStore (org.keycloak.authorization.store.PolicyStore)13