Permission-Based Authorization in Spring Security
Permission-based authorization checks what a user is allowed to do rather than what job title they have. Instead of asking "is this user a manager?", the code asks "may this user approve expense claims?" and, one step further, "may this user approve this claim?".
This tutorial builds both levels in Spring Security. Roles are mapped to permission strings that rules check with hasAuthority, and a custom PermissionEvaluator answers object-level questions through hasPermission. The example is an expense-claims system where managers may only approve claims from their own department and within their approval limit.
1. What Is Permission-Based Authorization?
A permission names one action, usually as resource:action, for example claim:approve. In Spring Security, permissions are ordinary GrantedAuthority strings without the ROLE_ prefix, so they are checked with hasAuthority (see role vs authority).
Permissions answer the type-level question ("can approve claims"). Real rules often depend on the specific record as well: its owner, department or amount. Spring Security supports this through the hasPermission(targetId, targetType, permission) expression in method security, which delegates to a PermissionEvaluator you write.
2. Why Use Permissions Instead of Roles?
- Stable code. Rules mention actions, which rarely change. Which roles include which actions can change in one place, without touching controllers or services.
- Least privilege. A new role, such as "regional manager", is just a new set of existing permissions.
- Real business rules. Object-level checks express limits that no role can, such as approval amounts and department boundaries.
3. How the Two Levels Work Together
The type-level check is cheap and runs first. Only when it passes does Spring evaluate hasPermission, which may need to load data. Both checks need method security to be enabled with @EnableMethodSecurity.
3.1 The PermissionEvaluator Interface
public interface PermissionEvaluator {
// hasPermission(#claim, 'approve'): you already have the object
boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission);
// hasPermission(#claimId, 'Claim', 'approve'): you only have its id and type
boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission);
}
4. A Complete Example: Expense Claim Approvals
Employees submit claims, managers approve claims from their own department up to their limit, and finance pays approved claims. Data is kept in memory to keep the focus on authorization. The example uses Java 21, Spring Boot 4.1.2 and Spring Security 7.1.2. The API is called by the company's internal client application with HTTP Basic and no cookies, so CSRF protection is disabled for it.
4.1 Permissions, Roles and Users
package com.javabytechie.expenses;
public enum Permission {
CLAIM_SUBMIT("claim:submit"),
CLAIM_APPROVE("claim:approve"),
CLAIM_PAY("claim:pay");
private final String authority;
Permission(String authority) {
this.authority = authority;
}
public String authority() {
return authority;
}
}
package com.javabytechie.expenses;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
// The only place that knows which role includes which permissions
public enum Role {
EMPLOYEE(Set.of(Permission.CLAIM_SUBMIT)),
MANAGER(Set.of(Permission.CLAIM_SUBMIT, Permission.CLAIM_APPROVE)),
FINANCE(Set.of(Permission.CLAIM_PAY));
private final Set<Permission> permissions;
Role(Set<Permission> permissions) {
this.permissions = permissions;
}
public List<GrantedAuthority> authorities() {
List<GrantedAuthority> result = new ArrayList<>();
result.add(new SimpleGrantedAuthority("ROLE_" + name()));
permissions.forEach(p -> result.add(new SimpleGrantedAuthority(p.authority())));
return result;
}
}
package com.javabytechie.expenses;
import java.util.Map;
import java.util.Optional;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
// Stands in for the HR database
@Component
public class StaffDirectory {
public record Staff(String username, String passwordHash, Role role,
String department, int approvalLimit) {}
private final Map<String, Staff> staff;
public StaffDirectory(PasswordEncoder encoder) {
staff = Map.of(
"ravi", new Staff("ravi", encoder.encode("ravi-pass"), Role.EMPLOYEE, "operations", 0),
"anita", new Staff("anita", encoder.encode("anita-pass"), Role.MANAGER, "operations", 10_000),
"farid", new Staff("farid", encoder.encode("farid-pass"), Role.FINANCE, "finance", 0));
}
public Optional<Staff> find(String username) {
return Optional.ofNullable(staff.get(username));
}
}
package com.javabytechie.expenses;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class StaffUserDetailsService implements UserDetailsService {
private final StaffDirectory directory;
public StaffUserDetailsService(StaffDirectory directory) {
this.directory = directory;
}
@Override
public UserDetails loadUserByUsername(String username) {
StaffDirectory.Staff s = directory.find(username)
.orElseThrow(() -> new UsernameNotFoundException("Unknown user"));
return User.withUsername(s.username())
.password(s.passwordHash())
.authorities(s.role().authorities()) // role plus its permissions
.build();
}
}
4.2 Object-Level Checks and the Service
package com.javabytechie.expenses;
import java.io.Serializable;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
@Component
public class ClaimPermissionEvaluator implements PermissionEvaluator {
private final ClaimRepository claims;
private final StaffDirectory directory;
public ClaimPermissionEvaluator(ClaimRepository claims, StaffDirectory directory) {
this.claims = claims;
this.directory = directory;
}
@Override
public boolean hasPermission(Authentication auth, Object target, Object permission) {
return target instanceof Claim claim && canApprove(auth, claim, permission);
}
@Override
public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
if (!"Claim".equals(targetType)) {
return false;
}
return claims.find((String) targetId)
.map(claim -> canApprove(auth, claim, permission))
.orElse(false);
}
private boolean canApprove(Authentication auth, Claim claim, Object permission) {
if (!"approve".equals(permission)) {
return false;
}
return directory.find(auth.getName())
.map(approver -> approver.department().equals(claim.department())
&& claim.amount() <= approver.approvalLimit()
&& !claim.owner().equals(approver.username())) // no self-approval
.orElse(false);
}
}
package com.javabytechie.expenses;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class ClaimService {
private final ClaimRepository claims;
public ClaimService(ClaimRepository claims) {
this.claims = claims;
}
@PreAuthorize("hasAuthority('claim:approve') and hasPermission(#claimId, 'Claim', 'approve')")
public Claim approve(String claimId) {
return claims.update(claimId, "APPROVED");
}
@PreAuthorize("hasAuthority('claim:pay')")
public Claim pay(String claimId) {
return claims.update(claimId, "PAID");
}
}
package com.javabytechie.expenses;
public record Claim(String id, String owner, String department, int amount, String status) {
}
package com.javabytechie.expenses;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.stereotype.Repository;
@Repository
public class ClaimRepository {
private final Map<String, Claim> claims = new ConcurrentHashMap<>(Map.of(
"C-1", new Claim("C-1", "ravi", "operations", 4_000, "SUBMITTED"),
"C-2", new Claim("C-2", "kiran", "operations", 25_000, "SUBMITTED"),
"C-3", new Claim("C-3", "neha", "sales", 3_000, "SUBMITTED")));
public Optional<Claim> find(String id) {
return Optional.ofNullable(claims.get(id));
}
public Claim update(String id, String status) {
return claims.computeIfPresent(id,
(key, c) -> new Claim(c.id(), c.owner(), c.department(), c.amount(), status));
}
}
4.3 Configuration and Controller
package com.javabytechie.expenses;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler;
import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableMethodSecurity
public class SecurityConfig {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/error").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults())
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(csrf -> csrf.disable()); // internal API client, no browser cookies
return http.build();
}
// Makes hasPermission(...) in @PreAuthorize use our evaluator
@Bean
static MethodSecurityExpressionHandler methodSecurityExpressionHandler(ClaimPermissionEvaluator evaluator) {
DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler();
handler.setPermissionEvaluator(evaluator);
return handler;
}
@Bean
PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}
}
package com.javabytechie.expenses;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClaimController {
private final ClaimService service;
public ClaimController(ClaimService service) {
this.service = service;
}
@GetMapping("/api/me")
public Map<String, Object> me(Authentication auth) {
List<String> authorities = auth.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.filter(a -> !a.startsWith("FACTOR_"))
.sorted().toList();
return Map.of("user", auth.getName(), "authorities", authorities);
}
@PostMapping("/api/claims/{id}/approve")
public Claim approve(@PathVariable String id) {
return service.approve(id);
}
@PostMapping("/api/claims/{id}/pay")
public Claim pay(@PathVariable String id) {
return service.pay(id);
}
}
package com.javabytechie.expenses;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ExpenseApplication {
public static void main(String[] args) {
SpringApplication.run(ExpenseApplication.class, args);
}
}
5. Step-by-Step Code Explanation
- Permissions and roles as enums.
Role.authorities()returns the role itself (ROLE_MANAGER) plus its permissions. Changing what managers may do means editing one enum constant. - Login builds the authorities.
StaffUserDetailsServicepasses the expanded list toUser.authorities(...), so after login every permission is an ordinary authority. - Type-level check.
hasAuthority('claim:approve')rejects users who may never approve anything, before any data is loaded. - Object-level check.
hasPermission(#claimId, 'Claim', 'approve')calls the four-argument method ofClaimPermissionEvaluator, which loads the claim and compares department, amount and owner with the approver's record. - Registering the evaluator. The static
MethodSecurityExpressionHandlerbean gives method security an expression handler that uses the evaluator. Declaring the methodstaticlets Spring create it early, before the method security infrastructure needs it. - The controller filters out
FACTOR_authorities (added by Spring Security 7 to record the login method) so the output shows only roles and permissions.
6. Expected Output
$ curl -u ravi:ravi-pass localhost:8080/api/me
HTTP/1.1 200
{"user":"ravi","authorities":["ROLE_EMPLOYEE","claim:submit"]}
$ curl -u anita:anita-pass localhost:8080/api/me
HTTP/1.1 200
{"user":"anita","authorities":["ROLE_MANAGER","claim:approve","claim:submit"]}
$ curl -u anita:anita-pass -X POST localhost:8080/api/claims/C-1/approve
HTTP/1.1 200
{"id":"C-1","owner":"ravi","department":"operations","amount":4000,"status":"APPROVED"}
$ curl -u anita:anita-pass -X POST localhost:8080/api/claims/C-2/approve
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:38.032Z","status":403,"error":"Forbidden","path":"/api/claims/C-2/approve"}
$ curl -u anita:anita-pass -X POST localhost:8080/api/claims/C-3/approve
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:38.099Z","status":403,"error":"Forbidden","path":"/api/claims/C-3/approve"}
$ curl -u ravi:ravi-pass -X POST localhost:8080/api/claims/C-1/approve
HTTP/1.1 403
{"timestamp":"2026-11-18T12:14:38.166Z","status":403,"error":"Forbidden","path":"/api/claims/C-1/approve"}
$ curl -u farid:farid-pass -X POST localhost:8080/api/claims/C-1/pay
HTTP/1.1 200
{"id":"C-1","owner":"ravi","department":"operations","amount":4000,"status":"PAID"}
Ravi's role expands to a single permission, Anita's to two. Anita approves claim C-1: same department, within her 10,000 limit. Claim C-2 is in her department but exceeds the limit, and C-3 belongs to sales, so both are refused by the evaluator with 403. Ravi is refused before the evaluator runs, because he lacks claim:approve. Farid pays C-1 with the claim:pay permission, and the response shows the status left by Anita's approval changing to PAID.
7. Advantages and Limitations
| Advantages | Limitations |
|---|---|
| Rules name actions, so they survive role changes | More authorities per user, and a mapping to maintain |
| Object checks express real business limits | hasPermission may load data on every call; watch performance |
| Evaluator logic is plain Java and easy to unit test | String targets and permissions are not type-checked at compile time |
| Fits naturally with RBAC: roles grant permissions | Very complex policies may need a dedicated policy engine |
8. Common Mistakes and Best Practices
- Using
hasRolefor permissions. Permissions have noROLE_prefix; usehasAuthority. - Forgetting to register the evaluator. Without the expression handler,
hasPermissionuses a default evaluator that always denies. - Doing only the object check. Combine it with a cheap type-level check so most denials avoid database calls.
- Returning
truefor unknown permissions or types. Default tofalse, as the evaluator above does. - Scattering the role-to-permission mapping. Keep it in one place: an enum, as here, or database tables for permissions that change at runtime.
9. Summary
- Permissions are authorities named after actions, such as
claim:approve, checked withhasAuthority. - Map roles to permissions in one place and expand them at login.
- Object-level rules use
hasPermissionin@PreAuthorizewith a customPermissionEvaluator. - Register the evaluator through a
MethodSecurityExpressionHandlerbean and enable@EnableMethodSecurity. - Run cheap type-level checks before object-level checks, and deny by default.
10. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between role-based and permission-based authorization?
Role-based rules check job titles such as ROLE_MANAGER. Permission-based rules check actions such as claim:approve. Roles usually grant a set of permissions, and code checks the permissions.
Q2. How does hasPermission work in Spring Security?
In a method security expression, hasPermission(...) delegates to the configured PermissionEvaluator. You can pass the object itself, or its id and type, along with the permission name.
Q3. How do I register a custom PermissionEvaluator?
Create a DefaultMethodSecurityExpressionHandler, call setPermissionEvaluator(...) with your evaluator, and expose the handler as a static @Bean of type MethodSecurityExpressionHandler.
Q4. Should permissions use the ROLE_ prefix?
No. Keep the prefix for roles only. Permissions are checked with hasAuthority, which compares the exact string.
Q5. Where should role-to-permission mappings be stored?
In one place. An enum works when permissions change only with releases; database tables work when administrators must change them at runtime. Either way, expand them into authorities when the user logs in.