00:00

Role vs Authority in Spring Security

Last updated:

Roles and authorities are the two words Spring Security uses for "what is this user allowed to do?", and the difference between them is mostly a naming convention. Both are stored as plain strings in GrantedAuthority objects. A role is simply an authority whose name starts with ROLE_.

That small prefix causes a large share of "why do I get 403?" questions. This tutorial explains exactly how hasRole and hasAuthority compare strings, shows when to use coarse roles and when to use fine-grained authorities, and demonstrates the common mistakes on a running newsroom application.

1. What Are Roles and Authorities?

A GrantedAuthority is an interface with one method, getAuthority(), which returns a string. After login, the user's Authentication carries a collection of them, and every authorization rule is a check against those strings.

By convention, Spring Security treats an authority starting with ROLE_ as a role, a broad job title such as ROLE_EDITOR. Other authorities usually describe a single permission, such as article:publish. The concept of RBAC itself is explained in role-based access control.

2. Role vs Authority: Key Differences

RoleAuthority (permission)
Stored asGrantedAuthority with ROLE_ prefix, e.g. ROLE_EDITORGrantedAuthority with any name, e.g. article:publish
MeaningWho the user is in the organisationOne specific action the user may perform
GranularityCoarse: few roles per userFine: many permissions per user or role
Rule methodshasRole("EDITOR"), hasAnyRole(...)hasAuthority("article:publish"), hasAnyAuthority(...)
Builder methodsUser.withUsername(..).roles("EDITOR") adds the prefix for you.authorities("article:publish") uses the string as it is
Typical useSimple apps, URL areas such as /admin/**Larger apps where roles change but permissions stay stable

3. How hasRole and hasAuthority Compare Strings

How hasRole and hasAuthority match authoritieshasRole("EDITOR") adds the ROLE_ prefix and looks for ROLE_EDITOR. hasAuthority("EDITOR") looks for the exact string EDITOR, which a user created with roles("EDITOR") does not have. User authorities ROLE_EDITOR, article:publish hasRole("EDITOR") looks for ROLE_EDITOR hasAuthority("EDITOR") looks for EDITOR Match: allowed No match: 403
Figure 1: hasRole adds ROLE_ before comparing; hasAuthority compares the exact string.
  • hasRole("EDITOR") prepends ROLE_ and checks for ROLE_EDITOR. In authorizeHttpRequests, passing "ROLE_EDITOR" is rejected with an error at startup, because the prefix would be doubled.
  • hasAuthority("EDITOR") checks for the exact string EDITOR.
  • User.withUsername(...).roles("EDITOR") stores ROLE_EDITOR; it throws an exception if the name already starts with ROLE_.
  • roles(...) and authorities(...) on the same builder replace each other. To give a user a role and permissions, pass them all to authorities(...), writing the role with its prefix.

3.1 Role Hierarchies

A RoleHierarchy bean lets one role include another, so an editor can do everything a reporter can without being given both roles. Since Spring Security 6.3, RoleHierarchyImpl has a builder, and authorizeHttpRequests and method security pick up the bean automatically:

Role hierarchy
@Bean
static RoleHierarchy roleHierarchy() {
    return RoleHierarchyImpl.withDefaultRolePrefix()
        .role("EDITOR").implies("REPORTER")
        .build();
}

If your organisation uses a prefix other than ROLE_, declare a GrantedAuthorityDefaults bean with the new prefix; hasRole will then use it.

4. A Complete Example: Newsroom Permissions

In a newsroom content system, reporters write drafts and editors review and publish them. Rules use a role where the job title is what matters and an authority where a specific permission is what matters. One rule contains a deliberate mistake, and one user is built with the builder mistake described above. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2.

package com.javabytechie.newsroom;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/error").permitAll()
                .requestMatchers("/api/articles/drafts").hasRole("REPORTER")
                .requestMatchers("/api/articles/review-queue").hasAuthority("article:publish")
                .requestMatchers("/api/articles/broken-rule").hasAuthority("EDITOR")  // mistake: no ROLE_
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults());
        return http.build();
    }

    // Editors can do everything reporters can
    @Bean
    static RoleHierarchy roleHierarchy() {
        return RoleHierarchyImpl.withDefaultRolePrefix()
            .role("EDITOR").implies("REPORTER")
            .build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    UserDetailsService users(PasswordEncoder encoder) {
        return new InMemoryUserDetailsManager(
            // Correct: role (with prefix) and permission in one authorities(...) call
            User.withUsername("maya").password(encoder.encode("maya-pass"))
                .authorities("ROLE_EDITOR", "article:publish").build(),
            User.withUsername("joel").password(encoder.encode("joel-pass"))
                .authorities("ROLE_REPORTER", "article:write").build(),
            // Mistake: authorities(...) replaces the role set by roles(...)
            User.withUsername("sara").password(encoder.encode("sara-pass"))
                .roles("EDITOR").authorities("article:publish").build());
    }
}

5. Step-by-Step Code Explanation

  1. Drafts use a role. Any reporter may read drafts, so hasRole("REPORTER") fits. Thanks to the hierarchy, editors pass too.
  2. The review queue uses an authority. Access depends on one permission, article:publish, not on a job title. If the newsroom later lets senior reporters publish, only their authorities change, not the rule.
  3. The broken rule. hasAuthority("EDITOR") looks for the string EDITOR, but Maya has ROLE_EDITOR. The correct rule would be hasRole("EDITOR") or hasAuthority("ROLE_EDITOR").
  4. The builder mistake. Sara is created with roles("EDITOR") followed by authorities("article:publish"). The second call replaces the first, so she loses her role.

6. Expected Output

First, the authorities each user really has:

Terminal
$ curl -u maya:maya-pass localhost:8080/api/whoami
HTTP/1.1 200
{"user":"maya","authorities":["FACTOR_PASSWORD","ROLE_EDITOR","article:publish"]}

$ curl -u joel:joel-pass localhost:8080/api/whoami
HTTP/1.1 200
{"user":"joel","authorities":["FACTOR_PASSWORD","ROLE_REPORTER","article:write"]}

$ curl -u sara:sara-pass localhost:8080/api/whoami
HTTP/1.1 200
{"user":"sara","authorities":["FACTOR_PASSWORD","article:publish"]}

Maya and Joel have their role and permission. Sara only has article:publish: her role is gone. Every user also has FACTOR_PASSWORD, an authority that Spring Security 7 adds to record that the user logged in with a password. It is an authority, not a role, and you can use it in rules that require a particular login method. Now the rules:

Terminal
$ curl -u joel:joel-pass localhost:8080/api/articles/drafts
HTTP/1.1 200
["Monsoon arrives early in Kerala","City budget: what changes"]

$ curl -u maya:maya-pass localhost:8080/api/articles/drafts
HTTP/1.1 200
["Monsoon arrives early in Kerala","City budget: what changes"]

$ curl -u joel:joel-pass localhost:8080/api/articles/review-queue
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:52.197Z","status":403,"error":"Forbidden","path":"/api/articles/review-queue"}

$ curl -u maya:maya-pass localhost:8080/api/articles/review-queue
HTTP/1.1 200
["City budget: what changes (ready for review)"]

$ curl -u maya:maya-pass localhost:8080/api/articles/broken-rule
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:52.333Z","status":403,"error":"Forbidden","path":"/api/articles/broken-rule"}

$ curl -u sara:sara-pass localhost:8080/api/articles/drafts
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:52.400Z","status":403,"error":"Forbidden","path":"/api/articles/drafts"}

Joel reads drafts as a reporter, and Maya reads them through the hierarchy. Joel lacks article:publish, so the review queue answers 403, while Maya passes. The broken rule rejects Maya even though she is an editor. Sara is rejected from drafts because the builder mistake removed her role.

7. Advantages and Limitations

ApproachStrengthsWeaknesses
Roles onlySimple to understand and manageRules break or multiply when job titles change
Authorities onlyPrecise, stable rulesMany strings to assign to each user
Roles that grant authoritiesAssign roles to users, check permissions in codeNeeds a mapping, usually in the database or a UserDetailsService

For larger systems, the third approach is usually best. Permission-based authorization shows how to build it.

8. Common Mistakes and Best Practices

  • Mixing up the prefix. Use hasRole("X") for roles and hasAuthority("ROLE_X") only if you must compare the full string.
  • Calling roles() and authorities() together. Put everything in one authorities(...) call.
  • Storing ROLE_ inconsistently in the database. Choose whether the prefix is stored or added in code, and apply it everywhere.
  • Granting many roles instead of using a hierarchy. A RoleHierarchy keeps user records small and rules readable.
  • Checking roles in business code. Prefer permissions in rules and annotations, so the code does not need to change when roles are reorganised.

9. Summary

  • Roles and authorities are both GrantedAuthority strings; a role is an authority with the ROLE_ prefix.
  • hasRole("X") checks ROLE_X; hasAuthority("X") checks X exactly.
  • roles(...) adds the prefix, and roles and authorities on one builder overwrite each other.
  • A RoleHierarchy bean lets higher roles include lower ones.
  • Spring Security 7 adds factor authorities such as FACTOR_PASSWORD to every login.

10. References