Search code examples
oauth-2.0keycloak

Keycloak not enforcing group authorization policies


I have set up two web applications (app1 and app2) and I am using Keycloak to handle authentication. To do this I set up 2 clients (client1 for app1, client2 for app2). So far this works fine and I am able to login to my apps.

But now I want to add some restrictions:

  • I have created 2 users (user1 and user2).
  • I want user1 to only have access to app1
  • I want user2 to only have access to app2
  • I will also have other users that will need access to both app1 and app2, sometimes at different levels. (e.g. user3 could be an admin user for app1 but a regular user for app2

To try and get this to work, I haver done the following

  • I have created 2 groups, user1 belongs to group1 and user2 belongs to group2.
  • Clients > client1/client2 > authorization > policies
    • Deleted existing policy
    • Create policy > group > configured the policies accordingly
  • Clients > client1/client2 > authorization > permissions > created a new permission
  • Authorization is enabled, standard authentication flow is enabled, implicit flow is disabled

Despite configuring all these settings, user1 and user2 can still login to both applications, its as if authorization is being ignored.

How do I get this to work??

Regarding the apps:

  • app1 is a web application running on Spring Boot 1.5
  • app2 is a web application running on Spring Boot 2.7
  • For both applications, I have configured properties like authorization-uri, token-uri, user-info-uri etc.

I am using keycloak 21.1.1.


Solution

  • I think I finally found what I was looking for...

    While KeyCloak lets you define roles for your application, it does not actually enforce these roles! Instead, these roles are passed to the application as part of the JWT Token. It is the applications responsibility to enforce these roles.

    In Spring Boot, an extra step is required. You need to create a class that implements GrantedAuthoritiesMapper in order to map the JWT roles to authorities in Spring Boot.