Skip to content
javahacks.dev
Security

Fix Spring Security 403 Forbidden on POST Requests

Fix a 403 Forbidden on POST, PUT and DELETE in Spring Security by sending the CSRF token, configuring it for APIs or checking roles and CORS preflight.

7 min read
Summarize in AI
Flat illustration of a security filter chain guarding a request, with the Spring Security, Spring Boot, Spring, OWASP and Okta logos.

GET requests work. The POST to the same endpoint returns 403 Forbidden, with the same credentials and the same URL. That asymmetry is the first clue, and in nine cases out of ten it points to one feature: Spring Security's CSRF protection, which is on by default and applies to POST, PUT, PATCH and DELETE but not to GET. The other cases are real authorization failures and a CORS preflight that never reached your controller. This post separates the four causes with the log line and the test that confirms each, gives the correct fix for browser forms and for stateless APIs and explains why the fix for one is a bug in the other. Examples use Spring Boot 4 and Spring Security 7.

Cause 1: the CSRF token is missing

Cross-site request forgery is an attack where another website makes the user's browser send a state-changing request to yours, carrying the user's session cookie automatically. Spring Security defends by requiring a secret token on every unsafe request, one an attacker's page cannot read. A request without the token is rejected with 403, before it reaches your controller. Turn on the debug log and send the request:

src/main/resources/application.yamlYAML
logging:
  level:
    org.springframework.security: DEBUG
Shell
curl -i -X POST http://localhost:8080/orders \
  -H 'Content-Type: application/json' \
  -u ada:change-me \
  -d '{"customerId":7,"totalCents":4999}'
Text
HTTP/1.1 403
Text
DEBUG o.s.security.web.csrf.CsrfFilter : Invalid CSRF token found for http://localhost:8080/orders
DEBUG o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code

Invalid CSRF token found is unambiguous. The authentication succeeded (basic auth was accepted), and the CSRF filter ran before authorization and refused the request. For a server-rendered page with a form, the fix is to include the token. Thymeleaf adds it automatically to th:action forms; in a plain HTML form or JSP, add the hidden field:

HTML
<form method="post" action="/orders">
  <input type="hidden" name="_csrf" value="${_csrf.token}"/>
  <button type="submit">Place order</button>
</form>

For a single-page application that calls the API with JavaScript from the same site, use the cookie-based repository: Spring writes the token to a cookie named XSRF-TOKEN that JavaScript can read, and the client sends it back in an X-XSRF-TOKEN header, a convention most HTTP libraries follow automatically:

src/main/java/dev/javahacks/security/SecurityConfig.javajava
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    http.csrf(csrf -> csrf
            .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
            .csrfTokenRequestHandler(new SpaCsrfTokenRequestHandler()));
    // ... authorization rules
    return http.build();
}

The reference on how the tokens work and the exact handler for single-page applications is in the CSRF section of the Spring Security documentation, and the attack itself, with prevention across a Spring or Jakarta application, is in preventing CSRF in Java apps. Do not turn the protection off to make the error go away for an application that uses cookies or sessions; see the next cause for when switching it off is correct.

Cause 2: a stateless API that does not need CSRF protection

CSRF works because the browser attaches credentials automatically. An API that authenticates with an Authorization: Bearer ... header, which a browser does not attach on its own, is not vulnerable in the same way: another site cannot make the user's browser add that header. For such an API the CSRF check protects nothing and breaks every non-browser client. Disable it, and make the API stateless so there is no session cookie to forge:

src/main/java/dev/javahacks/security/ApiSecurityConfig.javajava
@Bean
SecurityFilterChain api(HttpSecurity http) throws Exception {
    return http
            .securityMatcher("/api/**")
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(a -> a.anyRequest().authenticated())
            .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
            .build();
}

The condition that makes this safe is the second one. If the same application also accepts a session cookie or HTTP basic credentials from a browser on those paths, disabling CSRF opens the hole it closes. Keep the two worlds in separate filter chains with different securityMatcher patterns: CSRF on for the cookie-based web UI, off for the token-based API. A POST with a valid bearer token that now returns 401 instead of 403 has moved to a different problem, covered in fixing 401 Unauthorized responses.

Cause 3: the user lacks permission

Not every 403 is CSRF. The user is authenticated, passes the CSRF check, and an authorization rule denies the action. The log distinguishes it:

Text
DEBUG o.s.s.w.a.i.FilterSecurityInterceptor : Failed to authorize filter invocation [POST /admin/users] with attributes [hasRole('ADMIN')]
DEBUG o.s.s.w.access.AccessDeniedHandlerImpl : Responding with 403 status code

Failed to authorize and the required attribute hasRole('ADMIN') tell you what was demanded. The classic slip is the role prefix. hasRole('ADMIN') checks for the authority ROLE_ADMIN; hasAuthority('ADMIN') checks for exactly ADMIN. A user stored with the authority ADMIN is denied by hasRole('ADMIN'):

java
// The user's authorities are ["ADMIN"]; this rule looks for "ROLE_ADMIN"
.requestMatchers(HttpMethod.POST, "/admin/**").hasRole("ADMIN")

// Matches the stored authority exactly
.requestMatchers(HttpMethod.POST, "/admin/**").hasAuthority("ADMIN")

For JWTs the authority names are derived from claims: a scope claim of orders.write becomes SCOPE_orders.write. Print the authenticated principal's authorities to see what you actually have:

java
@GetMapping("/whoami")
Map<String, Object> whoami(Authentication auth) {
    return Map.of("name", auth.getName(), "authorities", auth.getAuthorities().toString());
}
Text
{"name":"ada","authorities":"[SCOPE_orders.read]"}

The user has SCOPE_orders.read and the rule demands write. The fix is in the token or the rule, depending on which is wrong. Also check the matcher order: first match wins, so a broad rule above a specific one hides it, and a method-specific rule (HttpMethod.POST) protects only POST, which is why GET works and POST does not. For method security with @PreAuthorize, the failure is an AccessDeniedException translated to the same 403. The authorization architecture is described in the authorization documentation.

Cause 4: a CORS preflight

A browser application on another origin sends a preflight OPTIONS request before a POST with a JSON body or custom headers. The preflight carries no credentials. If security is configured without CORS handling, the preflight is rejected with 403 and the browser never sends the real POST. In the browser's console this appears as a CORS error, but in the network tab you see the OPTIONS call failing:

Text
Access to fetch at 'http://localhost:8080/orders' from origin 'http://localhost:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check

The 403 is real and the cause is that CORS was not configured on the security filter chain. Enable it so the CORS filter runs before authorization and answers the preflight:

java
@Bean
SecurityFilterChain web(HttpSecurity http) throws Exception {
    return http
            .cors(Customizer.withDefaults())
            .authorizeHttpRequests(a -> a.anyRequest().authenticated())
            .build();
}

@Bean
CorsConfigurationSource corsConfigurationSource() {
    var cfg = new CorsConfiguration();
    cfg.setAllowedOrigins(List.of("http://localhost:5173"));
    cfg.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE"));
    cfg.setAllowedHeaders(List.of("Authorization", "Content-Type", "X-XSRF-TOKEN"));
    cfg.setAllowCredentials(true);
    var source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", cfg);
    return source;
}

Name allowed origins explicitly; * with credentials is rejected by browsers. The full set of CORS failures is in fixing Spring Boot CORS errors. Note that a CORS setup does not remove the CSRF requirement for cookie-based POSTs: allowed headers must include the CSRF header name.

Test it from the command line

Reproduce each case with curl to see which layer answers. First, get a token and a session the way a browser would:

Shell
curl -c jar.txt -s -o /dev/null http://localhost:8080/login-page
TOKEN=$(grep XSRF-TOKEN jar.txt | awk '{print $7}')
curl -i -b jar.txt -X POST http://localhost:8080/orders \
  -H "X-XSRF-TOKEN: $TOKEN" -H 'Content-Type: application/json' \
  -u ada:change-me -d '{"customerId":7,"totalCents":4999}'
Text
HTTP/1.1 201

With the token, the same request succeeds, which proves the earlier 403 was CSRF. If it still returns 403 with the debug line Failed to authorize, it is permission (cause 3). Test the preflight directly with curl -i -X OPTIONS -H 'Origin: http://localhost:5173' -H 'Access-Control-Request-Method: POST' http://localhost:8080/orders and look for Access-Control-Allow-Origin in the response. And write a security test so the behavior is pinned, using Spring Security's test support:

java
@Test
@WithMockUser("ada")
void postWithoutCsrfIsForbidden() throws Exception {
    mvc.perform(post("/orders").contentType(MediaType.APPLICATION_JSON).content("{}"))
       .andExpect(status().isForbidden());
}

@Test
@WithMockUser("ada")
void postWithCsrfIsAccepted() throws Exception {
    mvc.perform(post("/orders").with(csrf()).contentType(MediaType.APPLICATION_JSON)
            .content("{\"customerId\":7,\"totalCents\":4999}"))
       .andExpect(status().isCreated());
}

Where this does not apply

If the 403 comes from a gateway, load balancer or WAF in front of the application, none of the application logs mention it; compare with a request straight to the pod. If GET fails with 403 as well, the cause is authorization, not CSRF. And if the response is a Tomcat page about an invalid request, the container rejected something before Spring saw it, for example a path with an encoded character that the firewall in Spring Security (StrictHttpFirewall) refuses, which logs The request was rejected because the URL contained a potentially malicious String.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.