liveBook · Manning

ROLE_ prefix

As explained in Spring Security in Action, Second Edition

The ROLE_ prefix is the naming convention Spring Security uses to distinguish role authorities from other authorities.

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

How Spring Security in Action, Second Edition covers it

How deep it goes
Defines the naming rule, contrasts declaration with use, and recommends role-checking methods without detailing framework internals.
Examples
Uses ADMIN and MANAGER users, endpoint restrictions, curl requests, and a 403 Forbidden response.
What you can do after
Apply role-based endpoint restrictions by declaring prefixed roles and checking them with unprefixed names.
How it connects
Connects roles with authorities, GrantedAuthority, hasRole(), hasAnyRole(), and AuthorizationManager.

This explainer was generated by Manning's knowledge graph from the text of Spring Security in Action, Second Edition. The section links point to the parts of the book it draws on.