Careeroza
Roles vs Authorities
What is an Authority?
After a user logs in, Spring Security keeps an Authentication object in the SecurityContext. It holds a list of granted authorities: plain strings that say what this user is allowed to do. Authorization rules check this list.
- Authority: any permission string, usually fine-grained:
product:write,order:refund. - Role: an authority whose name starts with
ROLE_, usually coarse-grained:ROLE_ADMIN,ROLE_CUSTOMER. - Internally there is no separate "role" type. A role is just a
GrantedAuthoritywith theROLE_prefix.
ShopEase Users
ShopEase has three kinds of users. We will use them in every example of this level:
| User | Roles | Extra authorities | Can do |
|---|---|---|---|
| [email protected] | ROLE_CUSTOMER | - | Browse, manage own cart and orders |
| [email protected] | ROLE_SELLER | product:write | Add and edit own products |
| [email protected] | ROLE_ADMIN | order:refund, user:manage | Everything, including refunds and users |
Creating Authorities in Code
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
// roles("SELLER") adds the ROLE_ prefix for you -> ROLE_SELLER
UserDetails ravi = User.withUsername("[email protected]")
.password("{bcrypt}$2a$10$Fh3...")
.roles("SELLER")
.build();
// authorities(...) takes the exact strings, no prefix is added
UserDetails meera = User.withUsername("[email protected]")
.password("{bcrypt}$2a$10$9Kq...")
.authorities("ROLE_ADMIN", "order:refund", "user:manage")
.build();
GrantedAuthority a = new SimpleGrantedAuthority("product:write");Tip
Tip: Calling .roles(...) and then .authorities(...) on the same builder replaces the first list. Use .authorities(...) alone when you need both roles and permissions, and write the ROLE_ prefix yourself.