Sub topic 3
Configuring CORS for Browser Clients
Assume you know Spring Boot REST controllers, dependency injection, HTTP status codes, and the basic idea of JWTs. This chapter connects browser access with token-based API security.
Configuring CORS for Browser Clients
Cross-Origin Resource Sharing (CORS) controls which browser origins may call an API. An origin is the scheme, host, and port, such as https://app.example.com. Browsers send a preflight OPTIONS request before some cross-origin requests.
Allow only the origins and methods that your application needs:
@Bean
CorsConfigurationSource corsConfigurationSource() {
var config = new CorsConfiguration();
config.setAllowedOrigins(List.of("https://app.example.com"));
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
config.setAllowedHeaders(List.of("Authorization", "Content-Type"));
var source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/api/**", config);
return source;
}Enable CORS in the security chain with http.cors(...). Do not use * for production APIs unless the endpoint is intentionally public.
Protecting the API with JWT Bearer Tokens
A JSON Web Token (JWT) is a signed token containing claims. Configure the API as an OAuth2 resource server so Spring validates the token signature, issuer, and expiration.
spring.security.oauth2.resourceserver.jwt.issuer-uri=https://auth.example.com/realms/demoUse the scope authority derived from the token:
.requestMatchers(HttpMethod.GET, "/api/orders/**")
.hasAuthority("SCOPE_orders.read")
.oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))The authorization server issues tokens. The API should validate them, not create them.
Method-Level Security with `@PreAuthorize`
Path rules protect HTTP routes. Method security protects business operations even when another caller reaches the method:
@EnableMethodSecurity
@Configuration
class MethodSecurityConfig {}
@PreAuthorize("hasRole('ADMIN') or #owner == authentication.name")
public List<Order> findOrders(String owner) {
return repository.findByOwner(owner);
}Use method rules for ownership and other decisions that need method arguments.
Customizing 401 and 403 Responses
A 401 Unauthorized response means authentication is missing or invalid. A 403 Forbidden response means the caller is authenticated but lacks permission. Configure JSON handlers for clients instead of returning an HTML login page.
.exceptionHandling(errors -> errors
.authenticationEntryPoint((req, res, ex) -> res.sendError(401, "Unauthorized"))
.accessDeniedHandler((req, res, ex) -> res.sendError(403, "Forbidden")))Testing Secured Endpoints
Use spring-security-test with MockMvc. Test anonymous access, valid permissions, and insufficient permissions.
mvc.perform(get("/api/orders"))
.andExpect(status().isUnauthorized());
mvc.perform(get("/api/orders").with(jwt()))
.andExpect(status().isForbidden());
mvc.perform(get("/api/orders").with(user("alice").roles("USER")))
.andExpect(status().isOk());Security Headers and Hardening Checklist
- Keep HTTPS enabled in every deployed environment.
- Validate JWT issuer, signature, expiration, and required scopes.
- Keep CORS origins narrow.
- Disable CSRF only for a stateless API that does not use cookie authentication.
- Keep security headers enabled unless a documented requirement prevents them.
- Avoid logging bearer tokens or passwords.
Exercise
What status should an authenticated user receive when the endpoint requires SCOPE_orders.read, but the JWT lacks that scope?
Show answer
403 Forbidden.