2

Spring security allows us to authorize URLs with hasAnyAuthority(), hasAnyRole(), hasRole() if we set granted authorities. If I create a custom token enhancer where I can add additional information in my token, is there a way to make authorization with the additional information?

CustomTokenEnhancer:

public final class CustomTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(
            OAuth2AccessToken accessToken,
            OAuth2Authentication authentication) {
        Map<String, Object> additionalInfo = new HashMap<>();
        additionalInfo.put("company", "authorizeAPIsWithCompany");
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);
        return accessToken;
    }
}

is it possible authorize APIs based on above additional info key, value? If not, how should I approach this idea?

e.g.:

@Override
public void configure(HttpSecurity http) throws Exception {
     http
            .authorizeRequests()
  .antMatchers("/authorizedURL").hasCompany("authorizeAPIsWithCompany")
  .....

}
Eniss
  • 975
  • 2
  • 20
  • 40

1 Answers1

0

I think you can do what you want without using additional information. Additional information is not needed by the OAuth protocol. It's just useful for storing descriptive information. You should be able to achieve what you want with scopes, authorities and grant types for clients and also authorities(roles) for users. You can have a look at the Oauth2 spec (https://www.rfc-editor.org/rfc/rfc6749) for any further information.

You can also have different security strategies like MethodSecurityConfig:

@EnableGlobalMethodSecurity(prePostEnabled = true)
public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    @Override
    protected MethodSecurityExpressionHandler createExpressionHandler() {
        return new OAuth2MethodSecurityExpressionHandler();
    }
}

@PreAuthorize("hasRole('ADMIN') OR #oauth2.clientHasRole('AUTHORIZED-MERCHANT')")
@GetMapping(value = "authorized-url")
public ResponseEntity<List<Order>> getOrders() {
    return ResponseEntity.ok(orderService.getOrders());
}
Community
  • 1
  • 1