Last updated: 2023-01-19
How to add more roles in Spring Security
Did you know that you can save days or weeks of development time when starting new Spring Boot apps? br With Bootify you have the right helper at your side - get a runnable prototype in minutes and focus on your business logic instead. Best practices included.
Discover more
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.