Consider a Spring Boot web application that handles user data. Why is authorization a critical part of its security?
Think about what happens if anyone could access all parts of the app without restrictions.
Authorization controls what authenticated users are allowed to do. Without it, users might access or change data they shouldn't, risking security and privacy.
In a Spring Boot app using Spring Security, if a user without the required role tries to access a protected REST endpoint, what is the expected behavior?
Think about how Spring Security handles authorization failures for authenticated users.
When a user is authenticated but lacks permission, Spring Security responds with 403 Forbidden to indicate access is denied.
Which of the following Spring Boot controller method annotations correctly restricts access to users with the role 'ADMIN'?
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.RestController; @RestController public class AdminController { @PreAuthorize("hasRole('ADMIN')") public String adminOnly() { return "Welcome Admin"; } }
Remember Spring Security expects roles to be prefixed with 'ROLE_' internally, but the annotation uses 'hasRole' without prefix.
The annotation @PreAuthorize("hasRole('ADMIN')") correctly restricts access to users with the ADMIN role. Option C uses hasAuthority with a prefix which is valid but different. Option C restricts to USER role, and D allows all.
Given this Spring Security config snippet, why might unauthorized users still access protected URLs?
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().permitAll()
)
.formLogin();Look at the order and meaning of the authorization rules.
The rule anyRequest().permitAll() allows all requests not matched before to be accessed by anyone, so URLs outside /admin/** are open.
In Spring Security, when during the filter chain processing is authorization (access control) checked?
Think about the order: authentication first, then authorization.
Spring Security first authenticates the user, then checks if they have permission to access the resource before the controller handles the request.