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 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 a user must have a role assigned to them for the above code to work. 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 in JWT.

Role-based Access Control

Now that you know how to include the user role into the JWT access token, you can implement Role-based access control in your Spring Resource Server. To do that, read the “Role-based Access Control in Spring Authorization Server” tutorial next.

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!