Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Authorization and Method Security

Roles, Authorities and Role Hierarchies

Learn the difference between roles and authorities, the ROLE_ prefix rule, how hasRole and hasAuthority work, and how to model permissions and role hierarchies cleanly.

Authentication says who you are. Authorization says what you may do. In Spring Security the answer is built from GrantedAuthority objects: plain strings attached to the logged-in user. This lesson separates the two words people use for them, role and authority, shows the one naming rule that causes endless confusion, and teaches a way to model permissions that stays manageable as the application grows.

The real configuration is read-only; the examples that run are Java stand-ins for the checks, so you can try every rule.

One mechanism, two vocabularies

Everything is a GrantedAuthority; a role is just an authority whose name starts with ROLE_.

You write Stored authority Meaning
.roles("ADMIN") on a user ROLE_ADMIN A broad job title
.authorities("ROLE_ADMIN") ROLE_ADMIN Same thing, spelled out
.authorities("article:publish") article:publish A fine-grained permission

And the checks:

Check What it tests
hasRole("ADMIN") Authority ROLE_ADMIN (adds the prefix for you)
hasAnyRole("ADMIN", "EDITOR") Any of ROLE_ADMIN, ROLE_EDITOR
hasAuthority("article:publish") The exact string
hasAuthority("ROLE_ADMIN") Same as hasRole("ADMIN")

The golden rule: hasRole adds ROLE_, hasAuthority does not. A very common bug is hasRole("ROLE_ADMIN"). In current versions that is rejected at startup with a message telling you to drop the prefix; in older code it silently never matched.

Java
http.authorizeHttpRequests(a -> a
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .requestMatchers(HttpMethod.POST, "/articles/*/publish").hasAuthority("article:publish")
    .requestMatchers(HttpMethod.GET, "/articles/**").hasAnyAuthority("article:read", "ROLE_EDITOR")
    .anyRequest().authenticated());

The check, modeled

The stand-in below implements the prefix rule and the four checks. Edit the user's authority set to see which rules pass.

Java hasRole adds ROLE_, hasAuthority does not (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Roles or permissions?

A role answers "what kind of user is this?" (customer, editor, admin). A permission answers "what action is allowed?" (article:publish). Rules written against roles break whenever the business changes: when "editors may now publish", every hasRole("EDITOR") that guards a publish endpoint stays correct, but a new "senior editor" role means touching all of them.

The robust design has two layers:

  1. Code checks permissions (hasAuthority("article:publish")). These names change only when the feature changes.
  2. The database maps roles to permissions (see the join in JDBC user stores). Business can create or change roles without a deploy.

Naming conventions that age well: resource:action (invoice:approve), lower case, no spaces. Keep roles for coarse gates such as /admin/**.

Role hierarchies

Often one role includes another: every admin is also an editor, every editor is also a viewer. Instead of giving admins three roles, declare the hierarchy:

Java
@Bean
RoleHierarchy roleHierarchy() {
    return RoleHierarchyImpl.fromHierarchy("""
        ROLE_ADMIN > ROLE_EDITOR
        ROLE_EDITOR > ROLE_VIEWER
        """);
}

With this bean, a user holding only ROLE_ADMIN passes hasRole("VIEWER"). In Spring Security 6.3 and later the hierarchy is picked up by method security and URL authorization when the bean exists (for authorizeHttpRequests through the AuthorizationManager factory; check the version notes of your release if a rule seems to ignore it). The hierarchy expands the granted authorities before the check, so it works for both hasRole and hasAuthority("ROLE_VIEWER"). Hierarchies can also include fine-grained authorities (ROLE_EDITOR > article:write).

The expansion algorithm is a graph walk, which you can run:

Java Role hierarchy as reachable authorities (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The last line is a warning: a cycle terminates, but it silently makes a viewer an admin. Spring's own RoleHierarchyImpl also tolerates cycles, so review hierarchy changes like code that grants privileges, because it is.

Other special expressions

Expression Meaning
permitAll() Everyone, including anonymous
denyAll() Nobody
authenticated() Any logged-in user (including remember-me)
fullyAuthenticated() Logged in and not via remember-me
anonymous() Only anonymous users (for the login page, to redirect away users who are signed in)
access(AuthorizationManager) Custom logic, see the AuthorizationManager lesson

Reading the current authorities

In a controller or service:

Java
@GetMapping("/me")
Map<String, Object> me(Authentication auth) {
    return Map.of(
        "name", auth.getName(),
        "authorities", auth.getAuthorities().stream().map(GrantedAuthority::getAuthority).sorted().toList());
}

and in a Thymeleaf template with the sec:authorize="hasAuthority('article:publish')" attribute, which hides a button. Hiding is not security: the endpoint behind the button must still be protected, because a user can call it directly.

Common mistakes

  • Checking roles in business code with string comparisons scattered around; use @PreAuthorize (see method security) or a single service.
  • Granting ROLE_ADMIN as the default in test data and then forgetting that production data lacks it.
  • Putting a huge number of authorities into a JWT or session; the cookie or token grows. Prefer roles in the token and permission expansion on the server, or load them per request.
  • Using authority names that differ in case: the comparison is exact.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user was created with .roles("EDITOR"). Which check passes?

    roles("EDITOR") stores ROLE_EDITOR, and hasRole adds the same prefix. Passing ROLE_ yourself to hasRole is rejected.
  2. 2. Why design code checks around permissions such as article:publish instead of roles?

    Roles map to permissions in data, so business changes do not require code changes.
  3. 3. What does ROLE_ADMIN > ROLE_EDITOR mean in a hierarchy?

    Holding the higher role implicitly grants everything below it.
  4. 4. Hiding an admin button with sec:authorize protects the admin endpoint.

    UI hiding is convenience. Anyone can send the request manually.

Summary

  • Everything is a GrantedAuthority; a role is an authority with the ROLE_ prefix.
  • hasRole adds the prefix, hasAuthority does not.
  • Check fine-grained permissions in code and map roles to permissions in data.
  • Declare a RoleHierarchy to avoid assigning stacked roles, and review changes carefully.
  • UI hiding never replaces server-side authorization.

Next: Method security