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.
Jump into concepts and practice - no test required
@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@PreAuthorize annotation in Spring Boot?@PreAuthorize@PreAuthorize.@PreAuthorize controls access before method runs [OK]@PreAuthorize with logging or exception handling@PreAuthorize?hasRole('ADMIN') checks if the user has the 'ADMIN' role.hasAuthority('USER') checks for a different role, permitAll() allows everyone, and denyAll() denies everyone.hasRole('ROLE_NAME') to restrict by role [OK]hasRole with hasAuthoritypermitAll() when restriction is needed@PreAuthorize("hasRole('ADMIN')")
public String adminOnly() {
return "Welcome Admin";
}@PreAuthorize blocks method [OK]@PreAuthorize:@PreAuthorize("hasRole(ADMIN)")
public void secureMethod() { }hasRole expressionhasRole('ADMIN').@PreAuthorize is correct annotation, so no other errors.hasRole() [OK]@PreAuthorize with @PostAuthorize@PreAuthorize to allow access only if the user has either 'ADMIN' role or 'MANAGER' authority?@PreAuthorizeor to allow access if either condition is true.or correctly; @PreAuthorize("hasRole('ADMIN') and hasAuthority('MANAGER')") requires both roles which is stricter; @PreAuthorize("hasRole('ADMIN')") @PreAuthorize("hasAuthority('MANAGER')") is invalid to use two annotations; @PreAuthorize("permitAll()") allows everyone.@PreAuthorize [OK]@PreAuthorize annotationspermitAll() which allows everyone