00:00

Permission-Based Authorization in Spring Security

Last updated:

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

Type-level and object-level permission checksAt login, the user role is expanded into permission authorities. At call time, @PreAuthorize first checks hasAuthority claim:approve, then hasPermission calls ClaimPermissionEvaluator, which loads the claim and checks department, amount limit and ownership. Role MANAGER stored for the user Authorities after login ROLE_MANAGER, claim:submit, claim:approve @PreAuthorize hasAuthority('claim:approve') hasPermission(#claimId, 'Claim', 'approve') ClaimPermissionEvaluator same department, within limit, not own claim
Figure 1: roles expand into permissions at login; hasPermission adds a check on the specific record at call time.

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

PermissionEvaluator.java
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;
    }
}

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);
    }
}

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();
    }
}

5. Step-by-Step Code Explanation

  1. 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.
  2. Login builds the authorities. StaffUserDetailsService passes the expanded list to User.authorities(...), so after login every permission is an ordinary authority.
  3. Type-level check. hasAuthority('claim:approve') rejects users who may never approve anything, before any data is loaded.
  4. Object-level check. hasPermission(#claimId, 'Claim', 'approve') calls the four-argument method of ClaimPermissionEvaluator, which loads the claim and compares department, amount and owner with the approver's record.
  5. Registering the evaluator. The static MethodSecurityExpressionHandler bean gives method security an expression handler that uses the evaluator. Declaring the method static lets Spring create it early, before the method security infrastructure needs it.
  6. 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

Terminal
$ 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

AdvantagesLimitations
Rules name actions, so they survive role changesMore authorities per user, and a mapping to maintain
Object checks express real business limitshasPermission may load data on every call; watch performance
Evaluator logic is plain Java and easy to unit testString targets and permissions are not type-checked at compile time
Fits naturally with RBAC: roles grant permissionsVery complex policies may need a dedicated policy engine

8. Common Mistakes and Best Practices

  • Using hasRole for permissions. Permissions have no ROLE_ prefix; use hasAuthority.
  • Forgetting to register the evaluator. Without the expression handler, hasPermission uses 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 true for unknown permissions or types. Default to false, 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 with hasAuthority.
  • Map roles to permissions in one place and expand them at login.
  • Object-level rules use hasPermission in @PreAuthorize with a custom PermissionEvaluator.
  • Register the evaluator through a MethodSecurityExpressionHandler bean and enable @EnableMethodSecurity.
  • Run cheap type-level checks before object-level checks, and deny by default.

10. References