Roles vs authorities
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite has customers and admins, and next month a support team joins: it may read orders and change nothing. Before writing any rule, you need to know what Spring Security actually keeps for a signed-in user.
GrantedAuthority: an authority is a string
GrantedAuthority is the Spring Security interface for one permission of a user. Its one method, getAuthority(), returns that permission as a plain String, such as "ROLE_CUSTOMER" or "order:read".
Spring Security knows nothing about "customer" or "can ship orders"; it only compares names. The program gives Asha two names and asks the checks behind hasRole and hasAuthority a few questions.
Example 1 · AuthoritiesDemo: roles and permissions are both strings
Runs in: the roles-lab Maven project (spring-boot-starter-security 4.1.1)
package com.shoplite.lab.roles;
import java.util.List;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.authorization.AuthorityAuthorizationManager;import org.springframework.security.authorization.AuthorizationManager;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.AuthorityUtils;
/** Roles and authorities are the same thing underneath: strings. hasRole only adds "ROLE_" in front. */public class AuthoritiesDemo {
public static void main(String[] args) { List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("ROLE_CUSTOMER", "order:read"); Authentication asha = UsernamePasswordAuthenticationToken.authenticated("asha", null, authorities);
for (GrantedAuthority authority : asha.getAuthorities()) { System.out.println(authority.getClass().getSimpleName() + " -> \"" + authority.getAuthority() + "\""); } System.out.println();
check("hasRole(\"CUSTOMER\")", AuthorityAuthorizationManager.hasRole("CUSTOMER"), asha); check("hasAuthority(\"ROLE_CUSTOMER\")", AuthorityAuthorizationManager.hasAuthority("ROLE_CUSTOMER"), asha); check("hasAuthority(\"CUSTOMER\")", AuthorityAuthorizationManager.hasAuthority("CUSTOMER"), asha); check("hasAuthority(\"order:read\")", AuthorityAuthorizationManager.hasAuthority("order:read"), asha); check("hasRole(\"ADMIN\")", AuthorityAuthorizationManager.hasRole("ADMIN"), asha); check("hasAnyRole(\"CUSTOMER\", \"ADMIN\")", AuthorityAuthorizationManager.hasAnyRole("CUSTOMER", "ADMIN"), asha); }
private static void check(String rule, AuthorizationManager<Object> manager, Authentication who) { boolean granted = manager.authorize(() -> who, new Object()).isGranted(); System.out.printf("%-36s %s%n", rule, granted ? "granted" : "denied"); }}SimpleGrantedAuthority -> "ROLE_CUSTOMER"
SimpleGrantedAuthority -> "order:read"
hasRole("CUSTOMER") granted
hasAuthority("ROLE_CUSTOMER") granted
hasAuthority("CUSTOMER") denied
hasAuthority("order:read") granted
hasRole("ADMIN") denied
hasAnyRole("CUSTOMER", "ADMIN") grantedWhat this code does
AuthorityUtils.createAuthorityList(...)wraps each name in aSimpleGrantedAuthority; a role and a permission look exactly the same.hasRole("CUSTOMER")andhasAuthority("ROLE_CUSTOMER")give the same answer;hasAuthority("CUSTOMER")is denied because no authority is literally namedCUSTOMER.authorize(...)returns anAuthorizationResult;isGranted()is the yes or no that the security filters act on.
Your app chooses the names; Spring Security only compares them. That is why one rule style works for roles and for permissions alike. AuthorityAuthorizationManager is the class behind hasRole and hasAuthority rules, used here directly so each decision shows by itself.
spring-boot-starter-security and spring-boot-starter-oauth2-resource-server.hasRole vs hasAuthority, and the double-prefix mistake
A role is an authority whose name starts with ROLE_, such as ROLE_ADMIN. The rule hasRole("ADMIN") adds that prefix for you and looks for ROLE_ADMIN.
Written with or without the prefix, a role check can go wrong in two ways: one fails loudly, one silently. The program shows both and prints what each user ends up holding.
Example 2 · DoublePrefixDemo: ROLE_ twice, loud and quiet
Runs in: the roles-lab Maven project (spring-boot-starter-security 4.1.1)
package com.shoplite.lab.roles;
import java.util.Collection;import java.util.List;
import org.springframework.security.authorization.AuthorityAuthorizationManager;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.oauth2.jwt.Jwt;import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
/** The two ways to end up with "ROLE_" twice, and what each one does. */public class DoublePrefixDemo {
public static void main(String[] args) { // Mistake 1: the prefix in the rule. Spring refuses it at once. try { AuthorityAuthorizationManager.hasRole("ROLE_ADMIN"); } catch (IllegalArgumentException e) { System.out.println("hasRole(\"ROLE_ADMIN\") -> " + e.getClass().getSimpleName() + ": " + e.getMessage()); } System.out.println();
// Mistake 2: the prefix in the data. Nothing fails; the admin is simply denied. JwtGrantedAuthoritiesConverter converter = new JwtGrantedAuthoritiesConverter(); converter.setAuthoritiesClaimName("roles"); converter.setAuthorityPrefix("ROLE_");
showAdminCheck("token roles [\"ADMIN\"] ", tokenWithRoles(List.of("ADMIN")), converter); showAdminCheck("token roles [\"ROLE_ADMIN\"]", tokenWithRoles(List.of("ROLE_ADMIN")), converter); }
private static Jwt tokenWithRoles(List<String> roles) { return Jwt.withTokenValue("demo-token").header("alg", "HS256") .subject("1").claim("roles", roles).build(); }
private static void showAdminCheck(String label, Jwt jwt, JwtGrantedAuthoritiesConverter converter) { Collection<GrantedAuthority> authorities = converter.convert(jwt); Authentication admin = new JwtAuthenticationToken(jwt, authorities); boolean granted = AuthorityAuthorizationManager.hasRole("ADMIN") .authorize(() -> admin, new Object()).isGranted(); List<String> names = authorities.stream().map(GrantedAuthority::getAuthority).toList(); System.out.println(label + " -> authorities " + names + " -> hasRole(\"ADMIN\") " + (granted ? "granted" : "denied")); }}hasRole("ROLE_ADMIN") -> IllegalArgumentException: ROLE_ADMIN should not start with ROLE_ since ROLE_ is automatically prepended when using hasRole. Consider using hasAuthority instead.
token roles ["ADMIN"] -> authorities [ROLE_ADMIN] -> hasRole("ADMIN") granted
token roles ["ROLE_ADMIN"] -> authorities [ROLE_ROLE_ADMIN] -> hasRole("ADMIN") deniedWhat this code does
- Mistake 1, the prefix in the rule, fails immediately with an exception that even suggests the fix.
- Mistake 2, the prefix in the data, produces
ROLE_ROLE_ADMIN. No error is logged; the admin is simply denied, which is much harder to find. JwtGrantedAuthoritiesConverteris the same class ShopLite'sSecurityConfiguses, configured the same way.
To avoid both, store and send bare role names (ADMIN, CUSTOMER), add the prefix in exactly one place (for ShopLite, the token converter), and write rules with hasRole.
hasAuthority("ADMIN") is not a role check at all: it looks for an authority literally named ADMIN.
Find the bug
Find the prefix bug
Each snippet should let an admin in. Tap the wrong line, then check the fix.
A rule for admin-only product changes.
Round 1 of 3Fine-grained authorities vs coarse roles
A permission is a fine-grained authority that says what a user may do, such as product:write or order:ship. It has no ROLE_ prefix and is checked with hasAuthority.
A role says who someone is; a permission says what they may do. The program turns each role into the permissions it carries and prints who may do what.
Example 3 · PermissionsDemo: expanding roles into permissions
Runs in: the roles-lab Maven project (spring-boot-starter-security 4.1.1)
package com.shoplite.lab.roles;
import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.authorization.AuthorityAuthorizationManager;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.AuthorityUtils;
/** Fine-grained authorities: each role is expanded into the permissions it carries. */public class PermissionsDemo {
/** One place that says what each role may do. Rules then ask for a permission, not a role. */ private static final Map<String, List<String>> PERMISSIONS = Map.of( "CUSTOMER", List.of("order:read", "order:create"), "SUPPORT", List.of("order:read", "customer:read"), "ADMIN", List.of("order:read", "order:ship", "product:write", "customer:read"));
static List<GrantedAuthority> authoritiesFor(String role) { List<String> names = new ArrayList<>(); names.add("ROLE_" + role); // keep the role too, for hasRole rules names.addAll(PERMISSIONS.get(role)); return AuthorityUtils.createAuthorityList(names); }
public static void main(String[] args) { Map<String, Authentication> users = new LinkedHashMap<>(); users.put("asha (CUSTOMER)", user("asha", "CUSTOMER")); users.put("farhan (SUPPORT)", user("farhan", "SUPPORT")); users.put("admin (ADMIN)", user("admin", "ADMIN"));
List<String> needed = List.of("order:read", "customer:read", "product:write", "order:ship"); System.out.printf("%-18s", ""); needed.forEach(p -> System.out.printf("%-15s", p)); System.out.println(); users.forEach((label, who) -> { System.out.printf("%-18s", label); for (String permission : needed) { boolean granted = AuthorityAuthorizationManager.hasAuthority(permission) .authorize(() -> who, new Object()).isGranted(); System.out.printf("%-15s", granted ? "yes" : "-"); } System.out.println(); }); }
private static Authentication user(String name, String role) { return UsernamePasswordAuthenticationToken.authenticated(name, null, authoritiesFor(role)); }}order:read customer:read product:write order:ship asha (CUSTOMER) yes - - - farhan (SUPPORT) yes yes - - admin (ADMIN) yes yes yes yes
What this code does
PERMISSIONSis the single place that says what each role may do; rules only ever ask for a permission.- The support user can read customers but not change products, without any rule naming the
SUPPORTrole. authoritiesForkeepsROLE_...as well, sohasRolerules and permission rules can live side by side.
Imagine the support team again. With roles only, every rule must list hasAnyRole("ADMIN", "SUPPORT") in the right places. With permissions, rules ask for customer:read and one table says which roles carry it.
Roles are simpler and fit small apps: ShopLite has two kinds of users and a short access table, so it keeps plain roles. The extension at the end of the module project tries permissions.
Role hierarchy: ADMIN can do everything CUSTOMER can
A role hierarchy tells Spring Security that one role includes another, such as ADMIN implies STAFF and STAFF implies CUSTOMER. Checks then use the reachable authorities, not only the stored ones.
An admin should do everything staff can, and staff everything a customer can. The program builds that chain with RoleHierarchyImpl and runs the same hasRole("CUSTOMER") check twice.
Example 4 · RoleHierarchyDemo: what an admin can reach
Runs in: the roles-lab Maven project (spring-boot-starter-security 4.1.1)
package com.shoplite.lab.roles;
import java.util.Collection;import java.util.List;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.authorization.AuthorityAuthorizationManager;import org.springframework.security.core.Authentication;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.AuthorityUtils;
/** A role hierarchy: ADMIN implies STAFF, STAFF implies CUSTOMER. */public class RoleHierarchyDemo {
public static void main(String[] args) { RoleHierarchy hierarchy = RoleHierarchyImpl.withDefaultRolePrefix() .role("ADMIN").implies("STAFF") .role("STAFF").implies("CUSTOMER") .build();
List<GrantedAuthority> adminOnly = AuthorityUtils.createAuthorityList("ROLE_ADMIN"); Collection<? extends GrantedAuthority> reachable = hierarchy.getReachableGrantedAuthorities(adminOnly); System.out.println("Stored: " + names(adminOnly)); System.out.println("Reachable: " + names(reachable)); System.out.println();
Authentication admin = UsernamePasswordAuthenticationToken.authenticated("admin", null, adminOnly);
AuthorityAuthorizationManager<Object> plain = AuthorityAuthorizationManager.hasRole("CUSTOMER"); AuthorityAuthorizationManager<Object> withHierarchy = AuthorityAuthorizationManager.hasRole("CUSTOMER"); withHierarchy.setRoleHierarchy(hierarchy);
System.out.println("hasRole(\"CUSTOMER\") for admin, no hierarchy: " + (plain.authorize(() -> admin, new Object()).isGranted() ? "granted" : "denied")); System.out.println("hasRole(\"CUSTOMER\") for admin, with hierarchy: " + (withHierarchy.authorize(() -> admin, new Object()).isGranted() ? "granted" : "denied")); }
private static List<String> names(Collection<? extends GrantedAuthority> authorities) { return authorities.stream().map(GrantedAuthority::getAuthority).sorted().toList(); }}Stored: [ROLE_ADMIN]
Reachable: [ROLE_ADMIN, ROLE_CUSTOMER, ROLE_STAFF]
hasRole("CUSTOMER") for admin, no hierarchy: denied
hasRole("CUSTOMER") for admin, with hierarchy: grantedWhat this code does
getReachableGrantedAuthoritiesfollows the chain:ADMINreachesSTAFF, and through itCUSTOMER.- The same
hasRole("CUSTOMER")check is denied without the hierarchy and granted with it; the stored authorities did not change. - In an app you would declare
RoleHierarchyas a@Beaninstead of callingsetRoleHierarchyyourself.
In a Spring Boot app you declare the hierarchy once as a @Bean of type RoleHierarchy. In Spring Security 7, URL rules and method security both pick it up, so you stop repeating hasAnyRole("CUSTOMER", "ADMIN").
ShopLite does not use a hierarchy, on purpose. Its access table says an admin calling /api/v1/me/orders gets 403, because an admin account has no customer profile. A hierarchy would let admins into every customer rule, /me included. Use one only when "the higher role may do everything the lower role may" is true for every rule.
Predict the output
Predict the hierarchy check
The hierarchy is ADMIN implies STAFF implies CUSTOMER. Is the rule granted?
Round 1 of 3
The user holds only ROLE_STAFF.
ShopLite's roles: database to token claim to authorities
The roles claim is the field in ShopLite's token that holds the user's bare role names, such as ["ADMIN"]. A claim is one named value inside a token. On each request the converter turns it back into ROLE_ authorities.
In ShopLite a role travels from the user_role table into the token, and back into an authority on every request. This converter is the last step.
/** The token's "roles" claim ["CUSTOMER"] becomes the authority ROLE_CUSTOMER. */private static JwtAuthenticationConverter rolesFromToken() { JwtGrantedAuthoritiesConverter authorities = new JwtGrantedAuthoritiesConverter(); authorities.setAuthoritiesClaimName("roles"); authorities.setAuthorityPrefix("ROLE_"); JwtAuthenticationConverter converter = new JwtAuthenticationConverter(); converter.setJwtGrantedAuthoritiesConverter(authorities); return converter;}Example 5 · Log in and read the roles claim
Runs in: the shoplite-api Spring Boot project
curl -i -X POST http://localhost:8080/api/v1/auth/login \ -H "Content-Type: application/json" \ -d '{"email":"asha.rao@example.com","password":"asha-dev-password"}'# copy accessToken into ASHA (and the admin's into ADMIN), then look inside the payloadecho "$ASHA" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/nullHTTP/1.1 200
Content-Type: application/json
{"accessToken":"eyJraWQiOiJ1ajQwRGhSendCMmM1Umh2VnctRnRYX1hWcV9ZdzNwcnI0NW55OUVHTHBnIiwiYWxnIjoiSFMyNTYifQ.eyJpc3MiOiJzaG9wbGl0ZS1hcGkiLCJjdXN0b21lcklkIjoxLCJzdWIiOiIyIiwiZXhwIjoxNzkyMTM5NzAyLCJpYXQiOjE3OTIxMzg4MDIsInJvbGVzIjpbIkNVU1RPTUVSIl19.yHKvw-HTW74vhfPfjMYoaE-eScEahZgHv9ejHaOsGOQ","tokenType":"Bearer","expiresIn":900}
$ echo "$ASHA" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null
{"iss":"shoplite-api","customerId":1,"sub":"2","exp":1792139702,"iat":1792138802,"roles":["CUSTOMER"]}
$ echo "$ADMIN" | cut -d. -f2 | tr '_-' '/+' | base64 -d 2>/dev/null
{"iss":"shoplite-api","sub":"1","exp":1792139702,"iat":1792138802,"roles":["ADMIN"]}What this code does
- The payload holds
"roles":["CUSTOMER"]without the prefix, andcustomerIdonly for customer accounts; the admin's token has nocustomerId. subis the user id, not the e-mail: the token is only Base64, so it must not carry personal data.- On each request the converter turns
["CUSTOMER"]intoROLE_CUSTOMER, whichhasRole("CUSTOMER")rules match. (Security headers trimmed from the output.)
Example 6 · src/main/java/com/shoplite/auth/TokenService.java
Runs in: the shoplite-api Spring Boot project
package com.shoplite.auth;
import java.time.Clock;import java.time.Instant;import java.util.List;
import org.springframework.security.core.GrantedAuthority;import org.springframework.security.oauth2.jose.jws.MacAlgorithm;import org.springframework.security.oauth2.jwt.JwsHeader;import org.springframework.security.oauth2.jwt.JwtClaimsSet;import org.springframework.security.oauth2.jwt.JwtEncoder;import org.springframework.security.oauth2.jwt.JwtEncoderParameters;import org.springframework.stereotype.Service;
import com.shoplite.user.UserPrincipal;
/** Builds the signed access token for a user who has just proved their password. */@Servicepublic class TokenService {
private final JwtEncoder encoder; private final JwtProperties properties; private final Clock clock;
TokenService(JwtEncoder encoder, JwtProperties properties, Clock clock) { this.encoder = encoder; this.properties = properties; this.clock = clock; }
TokenResponse issue(UserPrincipal user) { Instant now = clock.instant(); // ROLE_CUSTOMER in Spring Security, "CUSTOMER" in the token (the converter adds the prefix back) List<String> roles = user.getAuthorities().stream() .map(GrantedAuthority::getAuthority) .filter(name -> name.startsWith("ROLE_")) .map(name -> name.substring("ROLE_".length())) .toList(); JwtClaimsSet.Builder claims = JwtClaimsSet.builder() .issuer(properties.issuer()) .subject(String.valueOf(user.getId())) // the user id, never the e-mail .issuedAt(now) .expiresAt(now.plus(properties.accessTokenTtl())) .claim("roles", roles); if (user.getCustomerId() != null) { claims.claim("customerId", user.getCustomerId()); // staff accounts have no customer row } JwsHeader header = JwsHeader.with(MacAlgorithm.HS256).build(); String token = encoder.encode(JwtEncoderParameters.from(header, claims.build())).getTokenValue(); return new TokenResponse(token, "Bearer", properties.accessTokenTtl().toSeconds()); }}TokenService has no output of its own. Its result is the token in the login response above:
{"accessToken":"eyJraWQiOi...","tokenType":"Bearer","expiresIn":900}What this code does
- It removes the
ROLE_prefix before writing the claim, so the token and the database both hold bare names and the converter adds the prefix back in one place. customerIdis added only when the account has a customer row; the Owner checks lesson uses it to find "my" orders.- This is the JWT module's
TokenService; the roles part is all this module needs from it.
Roles are read from the signed token, never from the request body, so a caller cannot promote themselves. Three settings matter:
setAuthoritiesClaimName("roles"): without it the converter reads the standardscopeclaim and you get no roles at all.setAuthorityPrefix("ROLE_"): without it the default prefix isSCOPE_, sohasRole("ADMIN")never matches.
Next step
Check your understanding
11 quick questions