The @PreAuthorize annotation helps control who can use certain parts of your app by checking user permissions before running a method.
@PreAuthorize annotation in Spring Boot
Start learning this pattern below
Jump into concepts and practice - no test required
@PreAuthorize("expression")
public ReturnType methodName(Parameters) {
// method code
}The expression inside quotes is a SpEL (Spring Expression Language) condition.
Common expressions check roles like hasRole('ROLE_ADMIN') or permissions like hasAuthority('PERMISSION').
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
// delete user code
}@PreAuthorize("#user.name == authentication.name")
public void updateProfile(User user) {
// update profile code
}@PreAuthorize("hasAuthority('READ_PRIVILEGE') and #id > 0")
public Data getData(Long id) {
// fetch data code
}This service has two methods. The deleteUser method only lets admins delete users. The updateProfile method lets users update their own profile by checking their username matches the logged-in user.
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @Service public class UserService { @PreAuthorize("hasRole('ADMIN')") public String deleteUser(Long id) { return "User " + id + " deleted."; } @PreAuthorize("#username == authentication.name") public String updateProfile(String username) { return "Profile updated for " + username; } }
Make sure to enable method security in your Spring Boot app with @EnableMethodSecurity.
Use hasRole('ROLE_NAME') or hasAuthority('AUTHORITY') depending on your security setup.
Expressions can access method parameters with #paramName and the current user with authentication.
@PreAuthorize checks permissions before running a method.
Use simple expressions to control access based on roles or user data.
It helps keep your app secure by limiting who can do what.
Practice
@PreAuthorize annotation in Spring Boot?Solution
Step 1: Understand the role of
This annotation is used to check if a user has the right role or permission before allowing method execution.@PreAuthorizeStep 2: Compare with other options
Logging, dependency injection, and exception handling are unrelated to@PreAuthorize.Final Answer:
To restrict access to methods based on user roles or permissions before execution -> Option CQuick Check:
Access control = A [OK]
@PreAuthorize controls access before method runs [OK]- Confusing
@PreAuthorizewith logging or exception handling - Thinking it injects dependencies
- Assuming it runs after method execution
@PreAuthorize?Solution
Step 1: Identify the correct expression for role checking
The expressionhasRole('ADMIN')checks if the user has the 'ADMIN' role.Step 2: Verify other options
hasAuthority('USER')checks for a different role,permitAll()allows everyone, anddenyAll()denies everyone.Final Answer:
@PreAuthorize("hasRole('ADMIN')") -> Option BQuick Check:
Role check syntax = D [OK]
hasRole('ROLE_NAME') to restrict by role [OK]- Using wrong role name or authority
- Confusing
hasRolewithhasAuthority - Using
permitAll()when restriction is needed
@PreAuthorize("hasRole('ADMIN')")
public String adminOnly() {
return "Welcome Admin";
}Solution
Step 1: Understand the role restriction
The method requires the user to have 'ADMIN' role to run.Step 2: Check user role and effect
User has 'USER' role, not 'ADMIN', so access is denied before method runs.Final Answer:
Access denied error is thrown before method runs -> Option AQuick Check:
Role mismatch causes denial = A [OK]
@PreAuthorize blocks method [OK]- Assuming method runs anyway
- Thinking it returns null instead of error
- Confusing roles 'USER' and 'ADMIN'
@PreAuthorize:@PreAuthorize("hasRole(ADMIN)")
public void secureMethod() { }Solution
Step 1: Check syntax of
The role name must be a string inside quotes:hasRoleexpressionhasRole('ADMIN').Step 2: Verify other options
Return type is not required,@PreAuthorizeis correct annotation, so no other errors.Final Answer:
Missing quotes around 'ADMIN' in hasRole expression -> Option DQuick Check:
Role names need quotes = C [OK]
hasRole() [OK]- Omitting quotes around role names
- Confusing
@PreAuthorizewith@PostAuthorize - Thinking method must return a value
@PreAuthorize to allow access only if the user has either 'ADMIN' role or 'MANAGER' authority?Solution
Step 1: Understand logical operators in
Use@PreAuthorizeorto allow access if either condition is true.Step 2: Analyze options
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGER')") usesorcorrectly; @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.Final Answer:
@PreAuthorize("hasRole('ADMIN') or hasAuthority('MANAGER')") -> Option AQuick Check:
Use 'or' for either role or authority = B [OK]
@PreAuthorize [OK]- Using 'and' instead of 'or' when either role suffices
- Trying to stack multiple
@PreAuthorizeannotations - Using
permitAll()which allows everyone
