0
0
Spring Bootframework~5 mins

Method-level security in Spring Boot

Choose your learning style9 modes available
Introduction

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.

You want to allow only certain users to run a specific function in your app.
You need to protect sensitive operations like deleting data or viewing private info.
You want to add security checks directly on service methods instead of the whole app.
You want to easily manage who can do what without changing your whole app setup.
Syntax
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.

Examples
This method can only be run by users with the ADMIN role.
Spring Boot
@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
    // delete user code
}
This method requires the user to have the READ_PRIVILEGE authority.
Spring Boot
@PreAuthorize("hasAuthority('READ_PRIVILEGE')")
public List<Item> getItems() {
    // return items
}
This method allows users to update only their own profile by comparing names.
Spring Boot
@PreAuthorize("#user.name == authentication.name")
public void updateProfile(User user) {
    // update profile code
}
Sample Program

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.

Spring Boot
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";
    }
}
OutputSuccess
Important Notes

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.

Summary

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.