Search in sources :

Example 31 with ResourceServer

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

the class ProtectionService method resource.

@Path("/resource_set")
public Object resource() {
    KeycloakIdentity identity = createIdentity(true);
    ResourceServer resourceServer = getResourceServer(identity);
    ResourceSetService resourceManager = new ResourceSetService(this.session, resourceServer, this.authorization, null, createAdminEventBuilder(identity, resourceServer));
    ResteasyProviderFactory.getInstance().injectProperties(resourceManager);
    ResourceService resource = new ResourceService(this.session, resourceServer, identity, resourceManager);
    ResteasyProviderFactory.getInstance().injectProperties(resource);
    return resource;
}
Also used : ResourceSetService(org.keycloak.authorization.admin.ResourceSetService) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) ResourceService(org.keycloak.authorization.protection.resource.ResourceService) ResourceServer(org.keycloak.authorization.model.ResourceServer) Path(javax.ws.rs.Path)

Example 32 with ResourceServer

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

the class ProtectionService method getResourceServer.

private ResourceServer getResourceServer(KeycloakIdentity identity) {
    String clientId = identity.getAccessToken().getIssuedFor();
    RealmModel realm = authorization.getKeycloakSession().getContext().getRealm();
    ClientModel clientModel = realm.getClientByClientId(clientId);
    if (clientModel == null) {
        clientModel = realm.getClientById(clientId);
        if (clientModel == null) {
            throw new ErrorResponseException("invalid_clientId", "Client application with id [" + clientId + "] does not exist in realm [" + realm.getName() + "]", Status.BAD_REQUEST);
        }
    }
    ResourceServer resourceServer = this.authorization.getStoreFactory().getResourceServerStore().findByClient(clientModel);
    if (resourceServer == null) {
        throw new ErrorResponseException("invalid_clientId", "Client application [" + clientModel.getClientId() + "] is not registered as a resource server.", Status.FORBIDDEN);
    }
    return resourceServer;
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) ErrorResponseException(org.keycloak.services.ErrorResponseException) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 33 with ResourceServer

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

the class ProtectionService method createIdentity.

private KeycloakIdentity createIdentity(boolean checkProtectionScope) {
    KeycloakIdentity identity = new KeycloakIdentity(this.authorization.getKeycloakSession());
    ResourceServer resourceServer = getResourceServer(identity);
    KeycloakSession keycloakSession = authorization.getKeycloakSession();
    RealmModel realm = keycloakSession.getContext().getRealm();
    ClientModel client = realm.getClientById(resourceServer.getId());
    if (checkProtectionScope) {
        if (!identity.hasClientRole(client.getClientId(), "uma_protection")) {
            throw new ErrorResponseException(OAuthErrorException.INVALID_SCOPE, "Requires uma_protection scope.", Status.FORBIDDEN);
        }
    }
    return identity;
}
Also used : RealmModel(org.keycloak.models.RealmModel) ClientModel(org.keycloak.models.ClientModel) KeycloakIdentity(org.keycloak.authorization.common.KeycloakIdentity) KeycloakSession(org.keycloak.models.KeycloakSession) ErrorResponseException(org.keycloak.services.ErrorResponseException) ResourceServer(org.keycloak.authorization.model.ResourceServer)

Example 34 with ResourceServer

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

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

the class PolicyEvaluationTest method testCheckUserClientRoles.

public static void testCheckUserClientRoles(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("testCheckUserClientRoles");
    StringBuilder builder = new StringBuilder();
    builder.append("var realm = $evaluation.getRealm();");
    builder.append("var roles = realm.getUserClientRoles('trinity', 'role-mapping-client');");
    builder.append("if (roles.size() == 1 && roles.contains('client-role-a')) { $evaluation.grant(); }");
    policyRepresentation.setCode(builder.toString());
    Policy policy = storeFactory.getPolicyStore().create(policyRepresentation, resourceServer);
    PolicyProvider provider = authorization.getProvider(policy.getType());
    DefaultEvaluation evaluation = createEvaluation(session, authorization, resourceServer, policy);
    provider.evaluate(evaluation);
    Assert.assertEquals(Effect.PERMIT, evaluation.getEffect());
}
Also used : Policy(org.keycloak.authorization.model.Policy) ClientModel(org.keycloak.models.ClientModel) JSPolicyRepresentation(org.keycloak.representations.idm.authorization.JSPolicyRepresentation) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) PolicyProvider(org.keycloak.authorization.policy.provider.PolicyProvider) StoreFactory(org.keycloak.authorization.store.StoreFactory) ResourceServer(org.keycloak.authorization.model.ResourceServer) DefaultEvaluation(org.keycloak.authorization.policy.evaluation.DefaultEvaluation)

Aggregations

ResourceServer (org.keycloak.authorization.model.ResourceServer)81 Policy (org.keycloak.authorization.model.Policy)50 Resource (org.keycloak.authorization.model.Resource)40 ClientModel (org.keycloak.models.ClientModel)37 Scope (org.keycloak.authorization.model.Scope)30 AuthorizationProvider (org.keycloak.authorization.AuthorizationProvider)26 StoreFactory (org.keycloak.authorization.store.StoreFactory)21 RealmModel (org.keycloak.models.RealmModel)20 UserModel (org.keycloak.models.UserModel)13 HashSet (java.util.HashSet)12 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)11 Map (java.util.Map)10 DefaultEvaluation (org.keycloak.authorization.policy.evaluation.DefaultEvaluation)10 PolicyProvider (org.keycloak.authorization.policy.provider.PolicyProvider)10 List (java.util.List)9 AdminPermissionManagement (org.keycloak.services.resources.admin.permissions.AdminPermissionManagement)9 ArrayList (java.util.ArrayList)8 Collection (java.util.Collection)8 HashMap (java.util.HashMap)8 ResourcePermission (org.keycloak.authorization.permission.ResourcePermission)8