Consider a Spring Boot REST controller with an endpoint secured to allow only users with the ADMIN role. A user authenticated with only the USER role tries to access this endpoint.
What will be the result?
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 { @PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin/data") public String getAdminData() { return "Sensitive admin data"; } }
Think about what Spring Security does when a user is authenticated but lacks the required role.
Spring Security returns HTTP 403 Forbidden when the user is authenticated but does not have the required role to access the endpoint.
Given a Spring Boot method, which of the following @PreAuthorize annotations correctly allows access only to users with role ADMIN or MANAGER?
Look for the annotation that checks if the user has any one of multiple roles.
The hasAnyRole expression checks if the user has at least one of the listed roles. The others are either invalid syntax or check for both roles simultaneously.
Review the following Spring Boot controller code. Despite the @PreAuthorize annotation, users without the ADMIN role can access the endpoint. What is the most likely cause?
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DebugController { @PreAuthorize("hasRole('ADMIN')") @GetMapping("/secure-data") public String secureData() { return "Top secret"; } }
Check if method-level security is activated in the application.
Without enabling method security (e.g., with @EnableMethodSecurity), the @PreAuthorize annotations are ignored, so role checks do not happen.
Given a Spring Boot endpoint secured with @PreAuthorize("hasRole('ADMIN')"), what will be the output if a user authenticated with roles USER and ADMIN accesses it?
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class MultiRoleController { @PreAuthorize("hasRole('ADMIN')") @GetMapping("/admin-area") public String adminArea() { return "Welcome Admin"; } }
Think about how Spring Security checks roles when multiple roles are present.
Spring Security grants access if the user has the required role, regardless of other roles they have.
In Spring Security, the hasRole('ROLE_NAME') method is used to check user roles. Which of the following statements about role prefixes is correct?
Consider the default behavior of Spring Security regarding role names.
By default, Spring Security adds the prefix "ROLE_" automatically when using hasRole, so you only specify the suffix.