Last updated: 2023-01-19

  1. Learn
  2. Next Steps
  3. Add Roles

How to add more roles in Spring Security

After adding Spring Security to our application, we may want to use additional roles besides ROLE_USER. What are the steps we need to take to make this happen?

In our implementation of the UserDetailsService, when an authentication attempt is made, the user is loaded from the database and provided as a Spring Security User object. Our object is at first populated as follows.

Adjusting our HttpUserDetailsService or JwtUserDetailsService

This always assigns a single, fixed role to the user. If, for example, we want to read all roles from the database, we could use the following logic instead.

Reading and assigning more roles to our user

With this change our user already possesses his new roles. If we protect our Spring Boot app with annotations, we can simply add @PreAuthorize("hasRole('" + ROLE_ADMIN + "')") to our endpoints. For a configuration-based definition, we instead customize HttpSecurityConfig or JwtSecurityConfig to our needs.

Requiring the ADMIN role for /backend/**

The Bootify Builder is a tool to create a modern Spring Boot application with custom database schema - directly in the browser. Spring Security for JWT or form-based is available in the Professional Plan.

Learn more
or see pricing