Is it possible to handle user authorization with multiple teams using Keyclaock?

Viewed 20

I'm new to keycloak and don't have its deep knowledge. We have to implement auth for an application in Spring Boot in which there are teams and a user can be part of different teams. He/user can have different roles/permissions for each team. For example, user A can be a manager for team1 and at the same time, he can be an admin for team2, etc.

I have implemented it in a way that there will be a keycloak client for each team. And client roles will be assigned to users as team permissions.

Now I want to restrict the APIs in such a way that only users with some permissions (roles assigned) for team1 can access data of the specific team (team1 in this case). I know we have @PreAuthroize annotation in Spring Boot in which I can add a check for 'hasRole', but it's not enough. It will simply check if a current user has this role or not, but I want to know do this user has this role for like team1 or for some other teams?

I can get the user roles for a specific client via keycloak admin API and manually check in the code if the role exists in assigned roles or not. See the code below:

Keycloak keycloak = keycloakClient.getInstance();
List<String> availableRoles = keycloak.realm(realm).users().get(user).roles().clientLevel(client).
                listAvailable().stream().map(role -> role.getName()).collect(Collectors.toList());
if (availableRoles.contains(Roles.TEAM_MANAGER.name())) {
    return true;
}

But I'm not sure if it is the right way or not.

The other option may be to not use keycloak for authorization (just use it for authentication) and have these roles in database tables and validate from DB if the user has the required role or not.

As I have already mentioned I'm not much experienced, so can anyone please suggest what is the right way for it?

1 Answers

You could have a look at this advanced tutorial I wrote.

It does not answer your very specific use-case, but It achieves something similar: write spring-security rules where users can do things on behalf of other users (instead of a team as you need).

PS

If you're using Keycloak adapters to map Keycloak roles to spring authorities, don't, it is deprecated.

Related