Add Roles to JWT Issued by Spring Authorization Server

In this blog post, you will learn how to add user Roles and Authorities to a JWT token issued by the new Spring Authorization Server.

When writing this tutorial, I assumed that you are familiar with the new Spring Configuration Server setup. Otherwise, please check the Spring Authorization Server tutorial first.

Adding Granted Authorities to JWT

To include user Roles and Granted Authorities to a JWT token, create a @Bean of the OAuth2TokenCustomizer data type. To do that, add the following method to any Java class annotated with @Configuration annotation.

@Bean
OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
    return context -> {
        if (context.getTokenType() == OAuth2TokenType.ACCESS_TOKEN) {
            Authentication principal = context.getPrincipal();
            Set<String> authorities = principal.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
            context.getClaims().claim("roles", authorities);
        }
    };
}

Please note that for the above code to work, a user will need to have a role assigned to them. Let’s learn how to assign a role to a new user.

Assign User a Role. In Memory User Details

There are different ways in which a new user can be created. Let’s assume that we need to create an in-memory user first.

@Bean
public UserDetailsService users() {
    
    PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
    
    UserDetails user = User.withUsername("sergey")
            .password(encoder.encode("password"))
            .roles("USER")
            .build();
    
    return new InMemoryUserDetailsManager(user);
    
}

Notice how a new role called “USER” is assigned to a newly created user. So now that you have added an OAuth2TokenCustomizer bean to your code, a newly acquired JWT for the above user should have a “roles” claim included.

I hope this tutorial is helpful to you.

For video lessons on how to secure your Spring Boot application with OAuth 2.0. and Spring Security 5, please checkout my complete video course OAuth 2.0. in Spring Boot applications.

Happy learning!