Jakub Janoštík
Jakub Janoštík

Reputation: 186

User based permissions/scopes in Spring oAuth2

In my current setup I have standalone spring oAuth2 server, standalone resource server and angularJs app with reverse proxy.

On the authentication server side I have register 2 clients (web-app and internal client for service communication). I correctly receive client scopes and Users roles.

Question 1 I need different permission (e.g. scopes) per user not client (web-app, mobile,...)

I tried providing my own ClientsDetailService where I would build ClientDetails for each user, but only thing I receive is client id ("web-app") and I have no way of knowing which user is logged in.

Is there a way to inject user context?

related stack question

Question 2 I can somehow work around this if I put all of the available permissions in the JWT and do the "hasPermission(...)" logic on the resource servers. Basically client app works in N scopes and server based on the Users role builds list of permissions and creates JWT. But...

Question 3 Is there a standard way of implementing more granular permission logic with spring oauth2? (think of 100+ different permissions with method level security)

Upvotes: 2

Views: 2181

Answers (1)

Jakub Janoštík
Jakub Janoštík

Reputation: 186

Ok, I finally managed to map custom scopes per user using TokenEnhancer as follows:

public class AuthorityTokenEnhancer implements TokenEnhancer {

@Override
public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    User user = (User) authentication.getPrincipal();

    final ImmutableMap<String, Object> additionalInfo = ImmutableMap.<String, Object>builder()
            .put("authorities", user.getAuthorities())
            .build();

    ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
    ((DefaultOAuth2AccessToken) accessToken).setScope(user.getPermissions());

    return accessToken;
}}

With this approach I can get currently logged in user and update scopes based on user permissions.

But still I don't know whether this is good practice or not.

Upvotes: 2

Related Questions