Spring Security uses the ROLE_ prefix to distinguish roles from other authorities. Roles represent coarse-grained privileges, while both roles and authorities use the GrantedAuthority contract. section 7.1.2
Use the convention consistently:
- Declare the role with its prefix, such as ROLE_ADMIN or ROLE_MANAGER. section 7.1.2
- Pass only the unprefixed name to hasRole(), such as hasRole("ADMIN"). section 7.1.2
- Prefer hasRole() or hasAnyRole(); use access() with AuthorizationManager when those methods do not fit. section 7.1.2
Listing 7.9 Setting roles for users
@Configuration
public class ProjectConfig {
@Bean
public UserDetailsService userDetailsService() {
var manager = new InMemoryUserDetailsManager();
var user1 = User.withUsername("john")
.password("12345")
.authorities("ROLE_ADMIN") #1
.build();
var user2 = User.withUsername("jane")
.password("12345")
.authorities("ROLE_MANAGER")
.build();
manager.createUser(user1);
manager.createUser(user2);
return manager;
}
// Omitted code
}
Shows users receiving ROLE_ADMIN and ROLE_MANAGER authorities. section 7.1.2
Restricting an endpoint
A user configured with ROLE_ADMIN can satisfy anyRequest().hasRole("ADMIN"). A user with ROLE_MANAGER receives HTTP 403 for that endpoint. section 7.1.2
