You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# HttpClient发送POST请求时CSRF令牌验证失败问题求助

Fixing the 403 Invalid CSRF Token Issue in Your POST Requests

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:

  1. On your first successful request, it sets an XSRF-TOKEN cookie in your response.
  2. 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 named X-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

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-Cookie entry with XSRF-TOKEN=<some-value>.
  • For the second request, ensure the cookie is being sent (look in the Request Headers' Cookie field). If it's missing, check the cookie's domain and path settings—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
});

If your frontend and backend are on different domains, the cookie's SameSite attribute might block it from being sent:

  • Ensure SameSite is set to Lax (for same-site or top-level navigation requests) or None (for cross-domain requests—requires HTTPS and the Secure cookie 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:00:31