Category: java
Spel in spring security method and authorization expression
Published on 30 Sep 2026
Explanation
Spring Security uses expression-based authorization to evaluate whether a user can access a protected resource.
Code:
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
// Delete user
}
Explanation
hasRole() can restrict a method to users with a specific role.
Code:
@PreAuthorize("hasRole('ADMIN')")
public void createUser(User user) {
// Only ADMIN can access
}
Explanation
hasAuthority() can check for a specific granted authority or permission.
Code:
@PreAuthorize("hasAuthority('USER_READ')")
public List<User> getUsers() {
return userService.findAll();
}
Explanation
Security expressions can access the currently authenticated principal and use it in authorization decisions.
Code:
@PreAuthorize("#username == authentication.name")
public User getProfile(String username) {
return userService.findByUsername(username);
}
Explanation
Multiple security conditions can be combined using logical operators in @PreAuthorize expressions.
Code:
@PreAuthorize("hasRole('ADMIN') or hasAuthority('USER_DELETE')")
public void deleteUser(Long id) {
userService.delete(id);
}