Search code examples
keycloakabackeycloak-services

ABAC with keycloak - Using Resource attributes in policy


What I am trying to achieve

Protect a resource in Keycloak with policy like:

if (resource.status == 'draft') $evaluation.grant(); 
else $evaluation.deny();

Going by their official documents and mailing list responses, it seems attribute based access control is possible, however, I could not find a way of getting it to work.

What I have tried

  • Using Authorization Services: I was unable to figure out where and how I can inject the attributes from the resource instance.
  • Using Authorization Context: I was hoping to get the policies associated with a resource and a scope so that I could evaluate them my self.

So far, I have managed to get no where with both approaches. To be honest, I have been overwhelmed by the terminology used in the Authorization services.

Question How can I use attributes of a resource instance while defining a policy in keycloak?


Solution

  • I solved this problem in Keycloak 4.3 by creating a JavaScript policy because Attribute policies don't exist (yet). Here is an example of the code I got working (note that the attribute values are a list, so you have to compare against the first item in the list):

    var permission = $evaluation.getPermission();
    var resource = permission.getResource();
    var attributes = resource.getAttributes();
    
    if (attributes.status !== null && attributes.status[0] == "draft") {
        $evaluation.grant();
    } else {
        $evaluation.deny();
    }