0
0
Spring Bootframework~5 mins

@Secured annotation in Spring Boot

Choose your learning style9 modes available
Introduction

The @Secured annotation helps protect parts of your app by allowing only certain users to access them.

You want to restrict access to a method based on user roles.
You need to protect admin-only features in your app.
You want to quickly add simple role-based security to service methods.
You want to prevent unauthorized users from calling sensitive functions.
Syntax
Spring Boot
@Secured({"ROLE_NAME"})
public void methodName() {
    // method code
}

Use role names with the prefix ROLE_ by convention.

You can specify multiple roles inside the braces as an array.

Examples
This method can only be accessed by users with the ROLE_ADMIN role.
Spring Boot
@Secured({"ROLE_ADMIN"})
public void adminOnly() {
    // admin code
}
This method allows access to users with either ROLE_USER or ROLE_ADMIN.
Spring Boot
@Secured({"ROLE_USER", "ROLE_ADMIN"})
public void userOrAdmin() {
    // code for users or admins
}
Sample Program

This service has two methods. One is only for admins, the other for users or admins.

Spring Boot
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;

@Service
public class DocumentService {

    @Secured({"ROLE_ADMIN"})
    public String getAdminDocument() {
        return "Secret Admin Document";
    }

    @Secured({"ROLE_USER", "ROLE_ADMIN"})
    public String getUserDocument() {
        return "User Document";
    }
}
OutputSuccess
Important Notes

You must enable method security in your Spring Boot app with @EnableMethodSecurity.

If a user does not have the required role, Spring Security will block access and throw an exception.

Roles should be granted to users in your security configuration or user database.

Summary

@Secured restricts method access by user roles.

Use role names with ROLE_ prefix inside curly braces.

Works well for simple role-based security in Spring Boot apps.