GrantedAuthority
About
In Spring Security, a GrantedAuthority
represents a permission or role granted to an authenticated user. It is used in authorization to determine if a user has access to a specific resource or action.
Spring Security does not differentiate between roles and permissions—they are both represented as GrantedAuthority
. However, by convention, roles are prefixed with "ROLE_"
(e.g., "ROLE_ADMIN"
).
Why is GrantedAuthority Important?
Defines user access levels – Controls what actions a user can perform.
Supports fine-grained permissions – Not limited to roles; can be specific permissions.
Works with Authentication objects – Used in
UserDetails
andAuthentication
.Facilitates role-based access control (RBAC) – Commonly used for securing resources
GrantedAuthority Interface
Spring Security provides the GrantedAuthority
interface:
Implementation Example
Spring Security provides a built-in implementation:
Where is GrantedAuthority Used?
1. In UserDetails Implementation
A UserDetails
object contains a collection of GrantedAuthority
representing the user's roles or permissions.
The
getAuthorities()
method returns roles or permissions for the user.
2. In Authentication Object
After authentication, Spring Security assigns GrantedAuthority
to the Authentication
object.
Retrieves the current user's roles or permissions.
3. In Security Expressions (@PreAuthorize
)
@PreAuthorize
)Spring Security uses GrantedAuthority
to control access at the method level.
Ensures only users with
"ROLE_ADMIN"
can invoke this method.
Role-Based vs Permission-Based Security
Approach
Example
Use Case
Role-Based Security
hasRole('ADMIN')
Grants access based on user roles.
Permission-Based Security
hasAuthority('READ_PRIVILEGE')
Grants access based on fine-grained permissions.
Using hasRole vs hasAuthority
hasRole('ADMIN')
→ Automatically adds"ROLE_"
prefix (expects"ROLE_ADMIN"
).hasAuthority('ROLE_ADMIN')
→ Requires exact match, including"ROLE_"
.
Using GrantedAuthority in Security Configuration
1. Hardcoded Roles in Memory (InMemoryUserDetailsManager)
Spring automatically converts
"ADMIN"
to"ROLE_ADMIN"
.
2. Fetching Roles from a Database
When using a database, roles are fetched dynamically.
Converts database roles into GrantedAuthority dynamically.
Changes in GrantedAuthority Handling wrt Spring Boot version
Feature
Spring Boot 2
Spring Boot 3
Security Config
Uses WebSecurityConfigurerAdapter
Uses Lambda-based SecurityFilterChain
Role Prefix Handling
roles("ADMIN")
adds "ROLE_"
automatically
No change
Method-Level Security
@PreAuthorize("hasRole('ADMIN')")
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
AuthenticationManager
configure(AuthenticationManagerBuilder auth)
@Bean AuthenticationManager
Spring Boot 2 Security Configuration Example
Spring Boot 3 Security Configuration Example
Uses lambda-based security configuration instead of
WebSecurityConfigurerAdapter
.
Last updated
Was this helpful?