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

Next.js与.NET后端CSRF验证报错:缺少RequestVerificationToken头

.NET与Next.js CSRF验证异常解决方案

核心疑问解答:为什么带了Cookie仍报错?

.NET的防伪验证采用双令牌配对机制:必须同时存在两个令牌才能通过验证——一个存储在Cookie中(由GetAndStoreTokens写入),另一个需要通过请求头或表单参数提交。仅携带Cookie时,后端无法完成令牌配对,因此会抛出The required antiforgery header value "RequestVerificationToken" is not present异常。

获取RequestVerificationToken的正确方式

调用antiforgery.GetAndStoreTokens(httpContext)时,该方法会返回AntiforgeryTokenSet对象,其中的RequestToken属性就是需要的RequestVerificationToken值。你需要将这个值通过API响应体返回给前端,示例代码:

var tokens = antiforgery.GetAndStoreTokens(httpContext);
return Ok(new { RequestVerificationToken = tokens.RequestToken });

前端拿到该值后,需在后续非GET请求(POST/PUT/DELETE等)中,将其放入RequestVerificationToken请求头。

AddAntiforgery配置调整建议

当前配置针对跨域场景是合理的,但需补充CORS配置以确保跨域凭证正常传递:

// 配置CORS
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowNextJs", policy =>
    {
        policy.WithOrigins("你的Next.js站点域名")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // 必须开启,否则跨域时Cookie无法携带
    });
});

// 启用CORS中间件(注意顺序:要在UseAntiforgery之前)
app.UseCors("AllowNextJs");

另外,SameSite=None和SecurePolicy=Always的配置是跨域场景下的正确设置,但需确保你的API和前端都使用HTTPS协议(SecurePolicy=Always要求Cookie仅在HTTPS环境下发送)。

Next.js前端示例代码

// 获取CSRF令牌
const fetchCsrfToken = async () => {
  const response = await fetch('https://你的API域名/api/csrf-token', {
    credentials: 'include' // 必须携带,否则无法接收Cookie
  });
  const data = await response.json();
  return data.RequestVerificationToken;
};

// 发送带CSRF验证的请求
const sendProtectedRequest = async () => {
  const csrfToken = await fetchCsrfToken();
  await fetch('https://你的API域名/api/protected-action', {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
      'RequestVerificationToken': csrfToken
    },
    body: JSON.stringify({ /* 请求数据 */ })
  });
};

内容的提问来源于stack exchange,提问作者ngruson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 11:05:04