Keycloak resource protection recommendations

Viewed 1168

I'm writing web services in Spring Boot and I use Keycloak to protect the application. The app will expose API to manage restaurants.

In Keycloak I have two roles: admin and manager.

A user with admin role can CRUD restaurants. The same company has multiple restaurants and each restaurant has a manager. I want users with manager role to be able to edit only their restaurant (the restaurant they manage).

According to my understanding of Keycloak's documentation I have to use Resource with Permission but they stated that:

[] you can also have a different resource named Alice’s Banking Account, which represents a single resource owned by a single customer, which can have its own set of authorization policies.

To do that I have to create a resource like this /api/restaurants/12345 but the thing is that I can't hardcode an ID like this.

For now I protected my endpoint like this in spring boot:

http
  .authorizeRequests()
  .mvcMatchers(HttpMethod.PUT, "/api/restaurants/*").hasAnyRole("ADMIN", "MANAGER")
  .anyRequest().permitAll();

This means that any manager from any restaurant can edit another restaurant. I want to limit that to their restaurant only (the restaurant they manage). How can I do that in Keycloak if at all possible?

1 Answers

What you are looking for is User managed access (UMA). It allows to manage the access permission for each resource.

The permissions can be managed with the user's authentication. So if a user enters a new restaurant you can automatically grant access permissions to him without involving a process with elevated privileges.

The best introduction is probably the Photoz example. Instead of restaurants, it's about photo albums.

Related