C# HttpClient发送POST请求时CSRF令牌验证失败问题求助
Hey Luca, let's work through this CSRF token problem you're hitting. Your first POST request succeeds, but the second throws a 403 because the server is getting a null CSRF token—even though you're carrying all cookies. Here's what's going on and how to fix it:
Why This Happens
Most likely, your server (looks like Spring Security from the error message) uses CSRF protection that works like this:
- On your first successful request, it sets an
XSRF-TOKENcookie in your response. - For subsequent state-changing requests (like your second POST to
/api/v1/rec), you need to send the value of that cookie either in a request header namedX-XSRF-TOKEN, or as a request parameter named_csrf.
You're carrying the cookie, but you're not passing its value back to the server in the required format—that's why it's seeing null.
Step-by-Step Fixes
1. Verify the XSRF-TOKEN Cookie Exists
First, confirm that the server actually set the cookie after your first request:
- In your browser's dev tools (Network tab), check the response headers of the first POST for a
Set-Cookieentry withXSRF-TOKEN=<some-value>. - For the second request, ensure the cookie is being sent (look in the Request Headers'
Cookiefield). If it's missing, check the cookie'sdomainandpathsettings—they need to match your second request's URL.
2. Pass the CSRF Token Correctly
Choose one of these methods to send the token back to the server:
Option A: Send it in the Request Header
This is the most common approach. Extract the XSRF-TOKEN cookie value and add it to your request headers. Here's an example with JavaScript/axios:
// Helper function to get the cookie value function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } // Make the second POST request axios.post('/api/v1/rec', yourRequestData, { withCredentials: true, // Ensures cookies are sent with the request headers: { 'X-XSRF-TOKEN': getCookie('XSRF-TOKEN') } });
If you're using curl for testing:
# First request: save cookies to a file curl -c cookie.txt -X POST https://your-server.com/api/first-endpoint # Extract the XSRF token from the cookie file XSRF_TOKEN=$(grep XSRF-TOKEN cookie.txt | awk '{print $7}') # Second request: send the token in the header and reuse cookies curl -b cookie.txt -H "X-XSRF-TOKEN: $XSRF_TOKEN" -X POST https://your-server.com/api/v1/rec -d "your-data-here"
Option B: Send it as a Request Parameter
If headers aren't feasible, add the token as a _csrf parameter in your POST body:
const token = getCookie('XSRF-TOKEN'); axios.post('/api/v1/rec', { ...yourRequestData, _csrf: token }, { withCredentials: true });
3. Check Cookie SameSite Settings
If your frontend and backend are on different domains, the cookie's SameSite attribute might block it from being sent:
- Ensure
SameSiteis set toLax(for same-site or top-level navigation requests) orNone(for cross-domain requests—requires HTTPS and theSecurecookie attribute).
4. Double-Check Server Configuration
While the error points to a client-side issue, it's worth confirming your server isn't applying inconsistent CSRF rules. For Spring Security, make sure /api/v1/rec isn't accidentally excluded from CSRF protection (though the error message suggests it's included).
Quick Recap
The key fix is: you have the XSRF-TOKEN cookie, but you need to send its value back to the server in either the X-XSRF-TOKEN header or _csrf parameter. Once you do that, the 403 should resolve.
内容的提问来源于stack exchange,提问作者Luca Sandri

