Consider a Spring Boot method annotated with @PreAuthorize("hasRole('ADMIN')"). What is the behavior if a user with role USER tries to call this method?
public class MyService { @PreAuthorize("hasRole('ADMIN')") public String adminOnlyMethod() { return "Secret Data"; } }
Think about what Spring Security does when authorization fails.
The @PreAuthorize annotation checks the user's roles before method execution. If the user lacks the required role, Spring Security throws an AccessDeniedException and prevents the method from running.
Choose the correct @PreAuthorize expression to allow access if the user has ROLE_ADMIN or ROLE_MANAGER.
Look for the expression that checks multiple roles correctly.
The hasAnyRole expression checks if the user has at least one of the listed roles. Using or with separate hasRole calls also works, but hasAnyRole is cleaner and correct. The other options have syntax errors or wrong logic.
Given the method below, what will be the output if the user has username "alice" and calls getUserData("alice")?
public class UserService { @PreAuthorize("#username == authentication.name") public String getUserData(String username) { return "Data for " + username; } }
Check how SpEL accesses method parameters and authentication info.
The SpEL expression #username == authentication.name compares the method parameter username with the current authenticated user's name. If they match, access is granted and the method returns the expected string.
Identify the problem in this annotation:
@PreAuthorize("hasRole('ADMIN') and hasPermission(#id, 'read')")Check the logical operators allowed in SpEL expressions.
In SpEL, logical AND must be written as &&, not and. Using and causes a syntax error.
Choose the statement that best describes the difference between @PreAuthorize and @PostAuthorize.
Think about when the security check happens relative to the method call.
@PreAuthorize runs before the method to decide if it should run. @PostAuthorize runs after the method and can check the returned data to decide if access is allowed.