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
@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.