Consider a Spring Boot method annotated with @Secured("ROLE_ADMIN"). What is the expected behavior if a user without the ROLE_ADMIN role tries to access this method?
import org.springframework.security.access.annotation.Secured; public class AdminService { @Secured("ROLE_ADMIN") public String getAdminData() { return "Sensitive Admin Data"; } }
Think about how Spring Security enforces role-based access control.
The @Secured annotation restricts method access to users with specified roles. If a user lacks the required role, Spring Security throws an AccessDeniedException to prevent unauthorized access.
Choose the correct syntax to allow access to a method for users with either ROLE_USER or ROLE_ADMIN using @Secured.
Remember that @Secured accepts an array of strings.
The @Secured annotation expects an array of role names as strings. The correct syntax uses curly braces to define the array: @Secured({"ROLE_USER", "ROLE_ADMIN"}).
A developer added @Secured("ROLE_ADMIN") to a method, but users without ROLE_ADMIN can still access it. What is the most likely cause?
import org.springframework.security.access.annotation.Secured; public class ReportService { @Secured("ROLE_ADMIN") public String generateReport() { return "Report Data"; } }
Check if method security is enabled in the Spring Security configuration.
For @Secured annotations to work, method security must be enabled by adding @EnableGlobalMethodSecurity(securedEnabled = true) in the configuration class. Without this, the annotations are ignored.
Given the method below, what will be the output if a user with only ROLE_USER calls it?
import org.springframework.security.access.annotation.Secured; public class DataService { @Secured({"ROLE_USER", "ROLE_ADMIN"}) public String fetchData() { return "Data fetched successfully"; } }
Check if the user's role matches any role in the annotation.
The @Secured annotation allows access if the user has any one of the specified roles. Since the user has ROLE_USER, the method executes and returns the string.
Both @Secured and @PreAuthorize annotations can restrict method access. What is a key advantage of using @PreAuthorize?
Think about flexibility in defining access rules.
@PreAuthorize allows using Spring Expression Language (SpEL) to write complex access rules, such as checking method parameters or combining roles with logical operators, which @Secured cannot do.