Search in sources :

Example 36 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class AbstractPolicyEnforcer method isAuthorized.

protected boolean isAuthorized(PathConfig actualPathConfig, MethodConfig methodConfig, AccessToken accessToken, OIDCHttpFacade httpFacade, Map<String, List<String>> claims) {
    Request request = httpFacade.getRequest();
    if (isDefaultAccessDeniedUri(request)) {
        return true;
    }
    Authorization authorization = accessToken.getAuthorization();
    if (authorization == null) {
        return false;
    }
    boolean hasPermission = false;
    Collection<Permission> grantedPermissions = authorization.getPermissions();
    for (Permission permission : grantedPermissions) {
        if (permission.getResourceId() != null) {
            if (isResourcePermission(actualPathConfig, permission)) {
                hasPermission = true;
                if (actualPathConfig.isInstance() && !matchResourcePermission(actualPathConfig, permission)) {
                    continue;
                }
                if (hasResourceScopePermission(methodConfig, permission)) {
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debugf("Authorization GRANTED for path [%s]. Permissions [%s].", actualPathConfig, grantedPermissions);
                    }
                    if (HTTP_METHOD_DELETE.equalsIgnoreCase(request.getMethod()) && actualPathConfig.isInstance()) {
                        policyEnforcer.getPathMatcher().removeFromCache(getPath(request));
                    }
                    return hasValidClaims(permission, claims);
                }
            }
        } else {
            if (hasResourceScopePermission(methodConfig, permission)) {
                hasPermission = true;
                return true;
            }
        }
    }
    if (!hasPermission && EnforcementMode.PERMISSIVE.equals(actualPathConfig.getEnforcementMode())) {
        return true;
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debugf("Authorization FAILED for path [%s]. Not enough permissions [%s].", actualPathConfig, grantedPermissions);
    }
    return false;
}
Also used : Authorization(org.keycloak.representations.AccessToken.Authorization) Request(org.keycloak.adapters.spi.HttpFacade.Request) Permission(org.keycloak.representations.idm.authorization.Permission)

Example 37 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class DecisionPermissionCollector method grantPermission.

protected void grantPermission(AuthorizationProvider authorizationProvider, Set<Permission> permissions, ResourcePermission permission, Collection<Scope> grantedScopes, ResourceServer resourceServer, AuthorizationRequest request, Result result) {
    Set<String> scopeNames = grantedScopes.stream().map(Scope::getName).collect(Collectors.toSet());
    Resource resource = permission.getResource();
    if (resource != null) {
        permissions.add(createPermission(resource, scopeNames, permission.getClaims(), request));
    } else if (!grantedScopes.isEmpty()) {
        ResourceStore resourceStore = authorizationProvider.getStoreFactory().getResourceStore();
        resourceStore.findByScope(grantedScopes.stream().map(Scope::getId).collect(Collectors.toList()), resourceServer.getId(), resource1 -> permissions.add(createPermission(resource, scopeNames, permission.getClaims(), request)));
        permissions.add(createPermission(null, scopeNames, permission.getClaims(), request));
    }
}
Also used : ResourceServer(org.keycloak.authorization.model.ResourceServer) ResourcePermission(org.keycloak.authorization.permission.ResourcePermission) Scope(org.keycloak.authorization.model.Scope) Permission(org.keycloak.representations.idm.authorization.Permission) Collection(java.util.Collection) AuthorizationRequest(org.keycloak.representations.idm.authorization.AuthorizationRequest) Set(java.util.Set) DecisionStrategy(org.keycloak.representations.idm.authorization.DecisionStrategy) ResourceStore(org.keycloak.authorization.store.ResourceStore) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Policy(org.keycloak.authorization.model.Policy) List(java.util.List) Map(java.util.Map) AuthorizationProvider(org.keycloak.authorization.AuthorizationProvider) LinkedHashSet(java.util.LinkedHashSet) Resource(org.keycloak.authorization.model.Resource) Resource(org.keycloak.authorization.model.Resource) ResourceStore(org.keycloak.authorization.store.ResourceStore)

Example 38 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class PermissionTicketAwareDecisionResultCollector method onGrant.

@Override
protected void onGrant(Permission grantedPermission) {
    // Removes permissions (represented by {@code ticket}) granted by any user-managed policy so we don't create unnecessary permission tickets.
    List<Permission> permissions = ticket.getPermissions();
    Iterator<Permission> itPermissions = permissions.iterator();
    while (itPermissions.hasNext()) {
        Permission permission = itPermissions.next();
        if (permission.getResourceId() == null || permission.getResourceId().equals(grantedPermission.getResourceId())) {
            Set<String> scopes = permission.getScopes();
            Iterator<String> itScopes = scopes.iterator();
            while (itScopes.hasNext()) {
                if (grantedPermission.getScopes().contains(itScopes.next())) {
                    itScopes.remove();
                }
            }
            if (scopes.isEmpty()) {
                itPermissions.remove();
            }
        }
    }
}
Also used : Permission(org.keycloak.representations.idm.authorization.Permission)

Example 39 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class PolicyEnforcerClaimsTest method testEnforceEntitlementAccessWithClaimsWithoutBearerToken.

@Test
public void testEnforceEntitlementAccessWithClaimsWithoutBearerToken() {
    initAuthorizationSettings(getClientResource("resource-server-test"));
    KeycloakDeployment deployment = KeycloakDeploymentBuilder.build(getAdapterConfiguration("enforcer-entitlement-claims-test.json"));
    PolicyEnforcer policyEnforcer = deployment.getPolicyEnforcer();
    HashMap<String, List<String>> headers = new HashMap<>();
    HashMap<String, List<String>> parameters = new HashMap<>();
    AuthzClient authzClient = getAuthzClient("enforcer-entitlement-claims-test.json");
    String token = authzClient.obtainAccessToken("marta", "password").getToken();
    AuthorizationContext context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());
    parameters.put("withdrawal.amount", Arrays.asList("50"));
    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());
    assertEquals(1, context.getPermissions().size());
    Permission permission = context.getPermissions().get(0);
    assertEquals(parameters.get("withdrawal.amount").get(0), permission.getClaims().get("withdrawal.amount").iterator().next());
    parameters.put("withdrawal.amount", Arrays.asList("200"));
    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertFalse(context.isGranted());
    parameters.put("withdrawal.amount", Arrays.asList("50"));
    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());
    parameters.put("withdrawal.amount", Arrays.asList("10"));
    context = policyEnforcer.enforce(createHttpFacade("/api/bank/account/1/withdrawal", token, headers, parameters));
    assertTrue(context.isGranted());
    assertEquals(1, context.getPermissions().size());
    permission = context.getPermissions().get(0);
    assertEquals(parameters.get("withdrawal.amount").get(0), permission.getClaims().get("withdrawal.amount").iterator().next());
}
Also used : AuthzClient(org.keycloak.authorization.client.AuthzClient) HashMap(java.util.HashMap) KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) Permission(org.keycloak.representations.idm.authorization.Permission) PolicyEnforcer(org.keycloak.adapters.authorization.PolicyEnforcer) List(java.util.List) AuthorizationContext(org.keycloak.AuthorizationContext) AbstractKeycloakTest(org.keycloak.testsuite.AbstractKeycloakTest) Test(org.junit.Test)

Example 40 with Permission

use of org.keycloak.representations.idm.authorization.Permission in project keycloak by keycloak.

the class UserManagedAccessTest method testScopePermissionsToScopeOnly.

@Test
public void testScopePermissionsToScopeOnly() throws Exception {
    ResourcePermissionRepresentation permission = new ResourcePermissionRepresentation();
    resource = addResource("Resource A", "marta", true, "ScopeA", "ScopeB");
    permission.setName(resource.getName() + " Permission");
    permission.addResource(resource.getId());
    permission.addPolicy("Only Owner Policy");
    getClient(getRealm()).authorization().permissions().resource().create(permission).close();
    AuthorizationResponse response = authorize("marta", "password", "Resource A", new String[] { "ScopeA", "ScopeB" });
    String rpt = response.getToken();
    assertNotNull(rpt);
    assertFalse(response.isUpgraded());
    AccessToken accessToken = toAccessToken(rpt);
    AccessToken.Authorization authorization = accessToken.getAuthorization();
    assertNotNull(authorization);
    Collection<Permission> permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertPermissions(permissions, "Resource A", "ScopeA", "ScopeB");
    assertTrue(permissions.isEmpty());
    try {
        response = authorize("kolo", "password", resource.getId(), new String[] { "ScopeA" });
        fail("User should not have access to resource from another user");
    } catch (AuthorizationDeniedException ade) {
    }
    PermissionResource permissionResource = getAuthzClient().protection().permission();
    List<PermissionTicketRepresentation> permissionTickets = permissionResource.findByResource(resource.getId());
    assertFalse(permissionTickets.isEmpty());
    assertEquals(1, permissionTickets.size());
    PermissionTicketRepresentation ticket = permissionTickets.get(0);
    assertFalse(ticket.isGranted());
    ticket.setGranted(true);
    permissionResource.update(ticket);
    response = authorize("kolo", "password", resource.getId(), new String[] { "ScopeA", "ScopeB" });
    rpt = response.getToken();
    assertNotNull(rpt);
    assertFalse(response.isUpgraded());
    accessToken = toAccessToken(rpt);
    authorization = accessToken.getAuthorization();
    assertNotNull(authorization);
    permissions = authorization.getPermissions();
    assertNotNull(permissions);
    assertPermissions(permissions, resource.getName(), "ScopeA");
    assertTrue(permissions.isEmpty());
    permissionTickets = permissionResource.findByResource(resource.getId());
    assertFalse(permissionTickets.isEmpty());
    // must have two permission tickets, one persisted during the first authorize call for ScopeA and another for the second call to authorize for ScopeB
    assertEquals(2, permissionTickets.size());
    for (PermissionTicketRepresentation representation : new ArrayList<>(permissionTickets)) {
        if (representation.isGranted()) {
            permissionResource.delete(representation.getId());
        }
    }
    permissionTickets = permissionResource.findByResource(resource.getId());
    assertEquals(1, permissionTickets.size());
}
Also used : AuthorizationDeniedException(org.keycloak.authorization.client.AuthorizationDeniedException) AccessToken(org.keycloak.representations.AccessToken) Permission(org.keycloak.representations.idm.authorization.Permission) PermissionTicketRepresentation(org.keycloak.representations.idm.authorization.PermissionTicketRepresentation) ArrayList(java.util.ArrayList) PermissionResource(org.keycloak.authorization.client.resource.PermissionResource) ResourcePermissionRepresentation(org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation) AuthorizationResponse(org.keycloak.representations.idm.authorization.AuthorizationResponse) Test(org.junit.Test)

Aggregations

Permission (org.keycloak.representations.idm.authorization.Permission)73 Test (org.junit.Test)50 AuthorizationResponse (org.keycloak.representations.idm.authorization.AuthorizationResponse)44 AccessToken (org.keycloak.representations.AccessToken)36 AuthorizationRequest (org.keycloak.representations.idm.authorization.AuthorizationRequest)29 ResourceRepresentation (org.keycloak.representations.idm.authorization.ResourceRepresentation)27 AuthorizationResource (org.keycloak.admin.client.resource.AuthorizationResource)23 AuthzClient (org.keycloak.authorization.client.AuthzClient)22 ClientResource (org.keycloak.admin.client.resource.ClientResource)20 ArrayList (java.util.ArrayList)19 ResourcePermissionRepresentation (org.keycloak.representations.idm.authorization.ResourcePermissionRepresentation)19 OAuthClient (org.keycloak.testsuite.util.OAuthClient)15 ScopePermissionRepresentation (org.keycloak.representations.idm.authorization.ScopePermissionRepresentation)14 JSPolicyRepresentation (org.keycloak.representations.idm.authorization.JSPolicyRepresentation)13 Response (javax.ws.rs.core.Response)12 AuthorizationDeniedException (org.keycloak.authorization.client.AuthorizationDeniedException)12 AccessTokenResponse (org.keycloak.representations.AccessTokenResponse)12 PermissionRequest (org.keycloak.representations.idm.authorization.PermissionRequest)12 PermissionResponse (org.keycloak.representations.idm.authorization.PermissionResponse)12 Authorization (org.keycloak.representations.AccessToken.Authorization)11