Return to site

🔐🍃 Advanced AUTHORIZATION in SPRING SECURITY: secure the method, NOT JUST the endpoint

· spring

🔸 TL;DR

In Spring Security, authorization is not only about protecting URLs.

Sometimes the real question is:

▪️ Can this user call this business method?

▪️ Can this user access this specific object?

▪️ Can this user see the returned data?

▪️ Can the rule live closer to the domain logic?

That is where method security becomes powerful. 🛡️

Section image

🔸 1. GET THE CURRENT USER FROM THE SECURITY CONTEXT

Authentication authentication =
 SecurityContextHolder.getContext().getAuthentication();
String username = authentication.getName();
Collection<? extends GrantedAuthority> authorities =
 authentication.getAuthorities();

The Security Context stores the current authenticated user.

You can read the username, roles, authorities, and custom authentication details from it. 👤

🔸 2. AUTHORIZE BEFORE EXECUTION WITH @PREAUTHORIZE

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long userId) {
 userRepository.deleteById(userId);
}

@PreAuthorize checks the rule BEFORE the method runs.

Here, only users with the ADMIN role can execute the delete operation. 🔒

🔸 3. CHECK OWNERSHIP BEFORE ACCESSING DATA

@PreAuthorize("hashtag#accountId == authentication.principal.accountId")
public Account getAccount(Long accountId) {
 return accountRepository.findById(accountId)
 .orElseThrow();
}

This protects data based on the current user.

The method runs only if the requested account belongs to the authenticated principal. 🧩

🔸 4. AUTHORIZE AFTER EXECUTION WITH @POSTAUTHORIZE

@PostAuthorize("returnObject.owner == authentication.name")
public Document getDocument(Long id) {
 return documentRepository.findById(id)
 .orElseThrow();
}

@PostAuthorize checks the rule AFTER the method returns.

Useful when authorization depends on the returned object, but use it carefully because the method already executed. 👀

🔸 5. ENABLE METHOD SECURITY

@Configuration
@EnableMethodSecurity
public class SecurityConfig {
}

This enables annotations like @PreAuthorize and @PostAuthorize.

Without method security enabled, these annotations will not protect your methods. ⚙️

🔸 WHY IT MATTERS

Endpoint security protects the door. 🚪

Method security protects the business action. ⚙️

Both matter.

A user may be allowed to call /accounts/{id}, but not allowed to access every account.

That difference is where real authorization begins.

🔸 TAKEAWAYS

▪️ Security Context gives access to the current authenticated user

▪️ @PreAuthorize protects methods before execution

▪️ @PostAuthorize protects returned data after execution

▪️ Method security is useful for ownership and business rules

▪️ URL security and method security are complementary

▪️ Authorization should answer: who can do what, on which data? 🔐

#SpringSecurity #SpringBoot #Java #Authorization #SecureCoding

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇