Search code examples
springspring-bootspring-securityjwtspring-security-oauth2

Where should roles not existing in a JWT be added to an Authentication object?


We have a Spring Boot server that authenticates users using JWT tokens. Users should be assigned roles based on their identity.

The server that grants tokens does not know what roles users should have in each system, so each system should grant roles based on the identify of the user.

Something like:

  1. Authenticate user.
  2. (User is authenticated) Look up which roles the user has and add to the Authentication in the security context.
  3. Check role. For instance, @PreAuthorize(hasRole('some_role'))

My question is:

How should I do this? Or alternatively, should I not do this and handle the situation in another way?


Solution

  • As was already mentioned, JwtAuthenticationConverter is the intended configuration point.

    Spring Security will pick it up as a @Bean:

    @Bean
    JwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtAuthenticationConverter converter =
            new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(...);
        return converter;
    }
    

    As was already pointed out in another answer, you can also set one on the DSL.

    You can read more in the reference: https://docs.spring.io/spring-security/site/docs/5.4.4/reference/html5/#oauth2resourceserver-jwt-authorization-extraction