What is the purpose of the @PreAuthorize annotation in Spring Security?
A) To check authorization before a method is invoked
B) To encrypt user passwords
C) To manage user sessions
D) To log user activities
Answer:
A) To check authorization before a method is invoked
Explanation:
The @PreAuthorize
annotation in Spring Security is used to perform authorization checks before a method is invoked. It allows you to define complex access control rules using SpEL (Spring Expression Language) expressions. This annotation is commonly used to secure service layer methods or controller endpoints by specifying conditions under which a method can be executed.
For example:
@PreAuthorize("hasRole('ROLE_USER') and #userId == authentication.principal.id")
public User getUser(Long userId) {
return userService.findById(userId);
}
In this example, the @PreAuthorize
annotation ensures that the getUser()
method can only be invoked if the authenticated user has the ROLE_USER
role and their ID matches the userId
passed to the method. This provides a powerful way to enforce security policies directly at the method level.