Role vs Authority in Spring Security
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
| Role | Authority (permission) | |
|---|---|---|
| Stored as | GrantedAuthority with ROLE_ prefix, e.g. ROLE_EDITOR | GrantedAuthority with any name, e.g. article:publish |
| Meaning | Who the user is in the organisation | One specific action the user may perform |
| Granularity | Coarse: few roles per user | Fine: many permissions per user or role |
| Rule methods | hasRole("EDITOR"), hasAnyRole(...) | hasAuthority("article:publish"), hasAnyAuthority(...) |
| Builder methods | User.withUsername(..).roles("EDITOR") adds the prefix for you | .authorities("article:publish") uses the string as it is |
| Typical use | Simple apps, URL areas such as /admin/** | Larger apps where roles change but permissions stay stable |
3. How hasRole and hasAuthority Compare Strings
hasRole("EDITOR")prependsROLE_and checks forROLE_EDITOR. InauthorizeHttpRequests, passing"ROLE_EDITOR"is rejected with an error at startup, because the prefix would be doubled.hasAuthority("EDITOR")checks for the exact stringEDITOR.User.withUsername(...).roles("EDITOR")storesROLE_EDITOR; it throws an exception if the name already starts withROLE_.roles(...)andauthorities(...)on the same builder replace each other. To give a user a role and permissions, pass them all toauthorities(...), 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:
@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());
}
}
package com.javabytechie.newsroom;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ArticleController {
@GetMapping("/api/whoami")
public Map<String, Object> whoami(Authentication authentication) {
List<String> authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority).sorted().toList();
return Map.of("user", authentication.getName(), "authorities", authorities);
}
@GetMapping("/api/articles/drafts")
public List<String> drafts() {
return List.of("Monsoon arrives early in Kerala", "City budget: what changes");
}
@GetMapping("/api/articles/review-queue")
public List<String> reviewQueue() {
return List.of("City budget: what changes (ready for review)");
}
@GetMapping("/api/articles/broken-rule")
public String brokenRule() {
return "Editors should see this, but the rule is wrong";
}
}
package com.javabytechie.newsroom;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class NewsroomApplication {
public static void main(String[] args) {
SpringApplication.run(NewsroomApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- Drafts use a role. Any reporter may read drafts, so
hasRole("REPORTER")fits. Thanks to the hierarchy, editors pass too. - 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. - The broken rule.
hasAuthority("EDITOR")looks for the stringEDITOR, but Maya hasROLE_EDITOR. The correct rule would behasRole("EDITOR")orhasAuthority("ROLE_EDITOR"). - The builder mistake. Sara is created with
roles("EDITOR")followed byauthorities("article:publish"). The second call replaces the first, so she loses her role.
6. Expected Output
First, the authorities each user really has:
$ 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:
$ 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
| Approach | Strengths | Weaknesses |
|---|---|---|
| Roles only | Simple to understand and manage | Rules break or multiply when job titles change |
| Authorities only | Precise, stable rules | Many strings to assign to each user |
| Roles that grant authorities | Assign roles to users, check permissions in code | Needs 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 andhasAuthority("ROLE_X")only if you must compare the full string. - Calling
roles()andauthorities()together. Put everything in oneauthorities(...)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
RoleHierarchykeeps 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
GrantedAuthoritystrings; a role is an authority with theROLE_prefix. hasRole("X")checksROLE_X;hasAuthority("X")checksXexactly.roles(...)adds the prefix, androlesandauthoritieson one builder overwrite each other.- A
RoleHierarchybean lets higher roles include lower ones. - Spring Security 7 adds factor authorities such as
FACTOR_PASSWORDto every login.
10. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between hasRole and hasAuthority?
hasRole("ADMIN") adds the ROLE_ prefix and checks for ROLE_ADMIN. hasAuthority("ADMIN") checks for the exact string ADMIN.
Q2. Why does hasAuthority("ADMIN") return 403 for an admin user?
Users created with roles("ADMIN") have the authority ROLE_ADMIN, not ADMIN. Use hasRole("ADMIN") or hasAuthority("ROLE_ADMIN").
Q3. Can I change the ROLE_ prefix?
Yes. Declare a GrantedAuthorityDefaults bean with your prefix, or an empty string for none. Role checks and the role hierarchy then use that prefix.
Q4. How do I give a user both roles and permissions with User.builder()?
Pass all of them to authorities(...), writing roles with the prefix, for example authorities("ROLE_EDITOR", "article:publish"). Calling roles(...) and authorities(...) on the same builder makes the later call replace the earlier one.
Q5. What is a role hierarchy in Spring Security?
A RoleHierarchy declares that one role includes others, for example that EDITOR implies REPORTER. Users with the higher role then pass checks for the lower one without having it assigned.