Consider a Spring Boot REST controller method secured with @PreAuthorize("hasRole('ADMIN')"). What happens if a user without the ADMIN role tries to access this endpoint?
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class AdminController { @GetMapping("/admin/data") @PreAuthorize("hasRole('ADMIN')") public String getAdminData() { return "Sensitive admin data"; } }
Think about what HTTP status code means 'access denied' due to insufficient permissions.
When a user is authenticated but lacks the required role, Spring Security returns HTTP 403 Forbidden. HTTP 401 is for unauthenticated users.
In Spring Security, which @PreAuthorize expression correctly allows access only to users with role USER or ADMIN?
Look for the expression that checks for multiple roles in one call.
hasAnyRole('USER', 'ADMIN') allows access if the user has at least one of the listed roles. The other options are either invalid syntax or require both roles.
After a user logs in, Spring Security stores authentication details. What does SecurityContextHolder.getContext().getAuthentication() return?
Think about what information Spring Security keeps about the current user.
The Authentication object holds the user's identity (principal), credentials (usually hidden), and roles (authorities). It does not expose passwords or user lists.
Given the following Spring Boot controller method, why does it allow access to users without the ADMIN role?
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping("/secure-data") @PreAuthorize("hasRole('ADMIN')") public String getData() { return "Secure Data"; } }
Check if method security annotations are activated in the configuration.
Spring Security requires enabling method security with @EnableMethodSecurity or similar. Without it, @PreAuthorize annotations are ignored.
In Spring Security, what is the key difference between hasRole('ADMIN') and hasAuthority('ADMIN') in access control expressions?
Think about how Spring Security stores roles internally with prefixes.
Spring Security stores roles with a 'ROLE_' prefix internally. hasRole('ADMIN') checks for 'ROLE_ADMIN', while hasAuthority('ADMIN') checks for 'ADMIN' exactly.