0
0
Spring Bootframework~5 mins

@PreAuthorize annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @PreAuthorize annotation helps control who can use certain parts of your app by checking user permissions before running a method.

You want to allow only admins to delete user accounts.
You want to let users see their own data but not others'.
You want to restrict access to certain features based on user roles.
You want to secure service methods in your backend.
You want to check permissions using simple expressions before method runs.
Syntax
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').

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 allows users to update only their own profile by comparing usernames.
Spring Boot
@PreAuthorize("#user.name == authentication.name")
public void updateProfile(User user) {
    // update profile code
}
This method requires the user to have a specific authority and a valid id.
Spring Boot
@PreAuthorize("hasAuthority('READ_PRIVILEGE') and #id > 0")
public Data getData(Long id) {
    // fetch data code
}
Sample Program

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.

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

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.

Summary

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