Roles vs authorities

Spring Security · lesson 8 of 31 · 3 min read

Stop guessing about the ROLE_ prefix and model permissions in a way that scales.

Open this lesson in the learning hub

Key points

  • A GrantedAuthority is just a string. Spring Security attaches no meaning to it.
  • A role is just an authority with the ROLE_ prefix. hasRole("ADMIN") looks for ROLE_ADMIN.
  • hasAuthority compares the string exactly, so it needs the full hasAuthority("ROLE_ADMIN").
  • A huge share of mystery 403s is a missing or doubled ROLE_ prefix. Pick one convention and store it consistently.
  • Coarse roles say who you are (ADMIN). Fine authorities say what you may do (post:delete). Check permissions in business code.

Example

// What you store on the user
new SimpleGrantedAuthority("ROLE_ADMIN");   // a role
new SimpleGrantedAuthority("post:delete");  // a permission

http.authorizeHttpRequests(a -> a
    .requestMatchers("/admin/**").hasRole("ADMIN")                 // matches ROLE_ADMIN
    .requestMatchers("/reports/**").hasAnyRole("ADMIN", "AUDITOR")
    .requestMatchers(HttpMethod.DELETE, "/api/posts/**")
        .hasAuthority("post:delete")                               // exact string
    .anyRequest().authenticated());

hasRole adds ROLE_ for you; hasAuthority does not. That one line explains most 403s.

This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Spring Security course, and every lesson in it is listed on the Spring Security contents page.