Consider a Spring Boot service method annotated with @PreAuthorize("hasRole('ADMIN')"). What is the behavior when a user without the ADMIN role tries to invoke this method?
public class UserService { @PreAuthorize("hasRole('ADMIN')") public String getAdminData() { return "Sensitive admin data"; } }
Think about what Spring Security does when access is denied at method level.
Spring Security checks the user's roles before method execution. If the user lacks the required role, it throws an AccessDeniedException and prevents the method from running.
Choose the correct Spring Security annotation to restrict access to a method so only users with the USER role can call it.
Remember the exact syntax for @PreAuthorize and role prefixes.
The @PreAuthorize annotation requires the role name with hasRole('ROLE_NAME'). The role prefix ROLE_ is added automatically, so just use hasRole('USER').
Given the following method secured with @PostAuthorize, what will be the output if the user has the ADMIN role?
public class ProductService { @PostAuthorize("returnObject.owner == authentication.name or hasRole('ADMIN')") public Product getProduct(int id) { return new Product(id, "Book", "user1"); } } // User 'admin' calls getProduct(1)
Think about what @PostAuthorize does after method execution.
@PostAuthorize checks the returned object after the method runs. Since the user has the ADMIN role, the condition passes and the product is returned.
Identify the syntax error in this Spring Security method annotation:
@PreAuthorize("hasRole('ADMIN') && hasPermission(#id, 'read')")Check the logical operators allowed in Spring Security SpEL expressions.
Spring Security SpEL uses and instead of && for logical AND. Using && causes a syntax error.
In Spring Security, method-level security is often implemented using proxies. Which statement below is true about how this affects method calls within the same class?
Think about how Spring AOP proxies work with self-invocation.
Spring AOP proxies intercept calls made from outside the bean. Internal calls within the same class do not go through the proxy, so security annotations are not applied in those cases.