🔸 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. 🛡️
🔸 1. GET THE CURRENT USER FROM THE SECURITY CONTEXT
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 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
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 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
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👇