How to Add Permission Based Access With PreAuthorize
Move from coarse roles to fine permissions in Spring Security with method security, custom bean checks, a meta annotation and tests for allow and deny.

A role check looks harmless at first: hasRole('ADMIN'). Six months later the codebase has ADMIN, SUPERADMIN, MANAGER, SUPPORT and a hasAnyRole on forty methods, and a request to let support staff refund orders under fifty dollars means editing every one of them. Roles describe who someone is. Access decisions are about what someone may do. Modelling the second directly, as permissions such as order:refund, makes the code say what it protects and moves the question of who gets which permission into data. This post builds it in Spring Security with method security: loading permissions, guarding methods, writing object level rules and testing all of it. The surrounding framework mechanics are in how the Spring Security filter chain works, and the simpler role based version is in role based access with Spring Security.
Roles, permissions and authorities
Spring Security has one concept for both, the GrantedAuthority, a string. A role is an authority with the prefix ROLE_, which hasRole('ADMIN') adds for you. A permission is just an authority without the prefix, checked with hasAuthority('order:refund'). A user can hold both, and the common design is to store roles in the database, map each role to a set of permissions and load the union as authorities at login:
@Service
public class DatabaseUserDetailsService implements UserDetailsService {
private final UserAccountRepository accounts;
public DatabaseUserDetailsService(UserAccountRepository accounts) {
this.accounts = accounts;
}
@Override
public UserDetails loadUserByUsername(String username) {
UserAccount account = accounts.findWithRoles(username)
.orElseThrow(() -> new UsernameNotFoundException(username));
Set<GrantedAuthority> authorities = new HashSet<>();
for (Role role : account.roles()) {
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.name()));
role.permissions().forEach(p -> authorities.add(new SimpleGrantedAuthority(p.code())));
}
return User.withUsername(account.username())
.password(account.passwordHash())
.authorities(authorities)
.disabled(!account.enabled())
.build();
}
}A MANAGER role then carries order:read, order:approve and order:refund; a SUPPORT role carries order:read and order:refund:small. Controllers and services only mention the permission strings, and changing who may refund is an edit to the role table. Keep the permission names in constants or an enum, so a typo fails to compile and not at run time:
public final class Permissions {
public static final String ORDER_READ = "order:read";
public static final String ORDER_APPROVE = "order:approve";
public static final String ORDER_REFUND = "order:refund";
private Permissions() {}
}Switch on method security
Method security is not on by default. Add the annotation to a configuration class. It enables @PreAuthorize, @PostAuthorize, @PreFilter and @PostFilter:
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}@EnableMethodSecurity replaced the older @EnableGlobalMethodSecurity; if you are upgrading, what changed in Spring Security 7 lists the differences. Then guard methods where the business rule lives, the service layer, and not only in controllers, because a service can be called from a scheduled job, a message listener or another controller:
@Service
public class OrderService {
@PreAuthorize("hasAuthority('order:read')")
public Order find(long id) { /* ... */ }
@PreAuthorize("hasAuthority('order:approve')")
public void approve(long id) { /* ... */ }
@PreAuthorize("hasAuthority('order:refund') and #amount <= 500")
public void refund(long id, BigDecimal amount) { /* ... */ }
}The annotation value is a Spring Expression Language expression evaluated before the method runs, with the method parameters available by name (#amount, which requires parameter names retained by the compiler, on by default in Spring Boot builds with -parameters). If the expression is false, Spring throws AuthorizationDeniedException before any of the method body executes, and the web layer turns it into a 403. For an unauthenticated caller the same check yields 401 through the entry point.
Object level rules belong in a bean
Permissions say what kind of action a user may perform. Many rules also depend on the specific object: a user may view only their own orders, a manager only those in their region. Putting that into an expression string becomes unreadable fast. Call a Spring bean instead, using @beanName in the expression:
@Component("orderAccess")
public class OrderAccess {
private final OrderRepository orders;
public OrderAccess(OrderRepository orders) {
this.orders = orders;
}
public boolean canView(long orderId, Authentication auth) {
if (has(auth, Permissions.ORDER_READ_ALL)) {
return true;
}
return orders.findOwnerId(orderId)
.map(owner -> owner.equals(currentUserId(auth)))
.orElse(false);
}
private boolean has(Authentication auth, String permission) {
return auth.getAuthorities().stream().anyMatch(a -> a.getAuthority().equals(permission));
}
private Long currentUserId(Authentication auth) {
return ((AppUser) auth.getPrincipal()).id();
}
}@PreAuthorize("@orderAccess.canView(#id, authentication)")
public Order find(long id) { /* ... */ }The rule is ordinary Java: testable, debuggable and reusable. authentication is a built in variable in the expression. For a rule that depends on the returned object, for example only returning the order if it belongs to the caller, use @PostAuthorize("returnObject.ownerId == authentication.principal.id"). It loads the object first and checks afterwards, so use it when the owner is not known before the load, and never when the method has side effects, because the side effects have already happened if the check fails.
A meta annotation for readability
Long expressions repeated across methods invite typos. Spring Security supports meta annotations: declare your own annotation that carries the @PreAuthorize, and the intent reads clearly at the use site.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@PreAuthorize("hasAuthority('order:approve')")
public @interface CanApprove {
}@CanApprove
public void approve(long id) { /* ... */ }The security rule now has one definition. Changing it, for example to require a second authority, is a one line edit. The mechanism of reading annotations is the one described in writing a custom annotation.
Collections: filtering results
When a method returns a list, a per-element permission check should happen where the data is fetched, as a query condition, not by loading everything and filtering. @PostFilter exists, and it filters in memory after the method returns, which is correct but loads rows the user may not see:
@PostFilter("hasAuthority('order:read:all') or filterObject.ownerId == authentication.principal.id")
public List<Order> findAll() { /* loads every order */ }For anything beyond small tables, push the rule into the query instead:
public List<Order> findVisible(AppUser user) {
return user.has(Permissions.ORDER_READ_ALL) ? orders.findAll() : orders.findByOwnerId(user.id());
}@PostFilter is a convenience for small, bounded collections.
Test allow, deny and anonymous
A secured method has three behaviours, and a good test covers all of them. @WithMockUser supplies an authenticated user with chosen authorities. For a service method, use a Spring test with method security active:
@SpringBootTest
class OrderServiceSecurityTest {
@Autowired OrderService service;
@Test
@WithMockUser(authorities = "order:approve")
void aUserWithThePermissionMayApprove() {
assertThatCode(() -> service.approve(1L)).doesNotThrowAnyException();
}
@Test
@WithMockUser(authorities = "order:read")
void aUserWithoutThePermissionIsDenied() {
assertThatThrownBy(() -> service.approve(1L)).isInstanceOf(AuthorizationDeniedException.class);
}
@Test
void anAnonymousCallerIsRejected() {
assertThatThrownBy(() -> service.approve(1L)).isInstanceOf(AuthenticationCredentialsNotFoundException.class);
}
@Test
@WithMockUser(authorities = "order:refund")
void theRefundLimitIsEnforced() {
assertThatThrownBy(() -> service.refund(1L, new BigDecimal("501"))).isInstanceOf(AuthorizationDeniedException.class);
}
}The boundary test, 501 against a 500 limit, is the one that catches an off by one in the expression. Add MockMvc tests for the controller layer to confirm the status codes, 403 for the denied user and 401 for the anonymous one, as described in fixing 403 Forbidden responses.
Pitfalls
Self invocation. Method security is applied through a proxy, so a call from one method to another in the same class bypasses the check. A public @PreAuthorize method called by a private helper inside the class is unprotected on that path. Put the guarded method behind a bean boundary.
Annotating only controllers. A rule on the controller does not protect a service that another entry point also calls.
Defaulting open. A method without an annotation is unprotected, silently. Consider denying by default at the URL layer, with anyRequest().authenticated(), and add an ArchUnit test that fails if a public service method lacks a security annotation.
Authorities in the token. If you use JWTs with permissions as claims, remember they are a snapshot: a revoked permission stays valid until the token expires, which argues for short lived access tokens, covered in refreshing tokens safely.
String typos. hasAuthority('order:aprove') fails closed, locking everyone out, which is the safe failure but a confusing one; the constants and a test per rule catch it.
When this does not apply
If the application has two roles and no object level rules, hasRole is simpler, and adding a permission table is over design. If your rules depend on many attributes, such as department, time and data sensitivity, attribute based access control in a policy engine like Open Policy Agent, or a dedicated authorisation service, scales better than expressions in annotations. The reference is the Spring Security method security documentation, and the OWASP guidance on authorization explains why checks belong on the server for every request.


