Method-level security helps protect specific parts of your app by controlling who can use certain methods. It keeps your app safe by checking permissions right where the action happens.
Method-level security in Spring Boot
@PreAuthorize("hasRole('ROLE_NAME')")
public ReturnType methodName(Parameters) {
// method code
}@PreAuthorize is an annotation that checks permissions before the method runs.
You can use expressions like hasRole('ROLE_NAME') to specify who can access the method.
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
// delete user code
}@PreAuthorize("hasAuthority('READ_PRIVILEGE')") public List<Item> getItems() { // return items }
@PreAuthorize("#user.name == authentication.name")
public void updateProfile(User user) {
// update profile code
}This service has two methods. viewAccount can be used by users with the USER role. deleteAccount can only be used by ADMINs. This shows how to protect methods based on roles.
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @Service public class AccountService { @PreAuthorize("hasRole('USER')") public String viewAccount() { return "Account details visible"; } @PreAuthorize("hasRole('ADMIN')") public String deleteAccount() { return "Account deleted"; } }
Enable method security in your Spring Boot app by adding @EnableMethodSecurity on a configuration class.
Use @PreAuthorize for checks before method runs, and @PostAuthorize for checks after method runs.
Make sure your security context is properly set up so roles and authorities are recognized.
Method-level security controls access to specific methods in your app.
Use @PreAuthorize with role or authority checks to protect methods.
This helps keep your app safe by checking permissions right where actions happen.