Concept Flow - @PreAuthorize annotation
Method call request
Check @PreAuthorize expression
Allow method
Return result
When a method is called, Spring checks the @PreAuthorize expression. If true, it runs the method; if false, it blocks access.
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser() {
// delete logic
}| Step | Action | Expression Evaluated | Result | Method Access |
|---|---|---|---|---|
| 1 | User calls deleteUser() | hasRole('ADMIN') | true | Allowed |
| 2 | Method deleteUser() runs | - | - | User deleted |
| 3 | User calls deleteUser() | hasRole('ADMIN') | false | Denied |
| 4 | Access denied exception thrown | - | - | Access denied |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| UserRole | unknown | ADMIN | USER | unchanged |
| AccessGranted | false | true | false | depends on role |
@PreAuthorize("expression")
- Checks security before method runs
- Expression uses roles or permissions
- If true, method runs
- If false, access denied exception
- Used for method-level security in Spring