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

表单外实现Anti-Forgery Token遇400错误:令牌验证失败求助

Anti-Forgery Token验证失败(400错误)排查与解决方案

核心问题分析

当前实现存在关键错误:将Anti-Forgery Cookie的值直接作为请求头令牌发送。ASP.NET Core的Anti-Forgery机制依赖Cookie令牌和**请求令牌(Header/Form字段)**的配对验证,两者是不同的值,不能直接复用Cookie内容。

具体排查与修复步骤

1. 确保页面已生成完整的Anti-Forgery令牌对

服务器需要先向客户端发送配对的Cookie和请求令牌,否则无法完成验证。在主布局页(如_Layout.cshtml)中添加以下代码,触发令牌生成:

@Html.AntiForgeryToken()

这行代码会生成一个隐藏的<input>元素(name为你配置的AntiforgeryFieldname),同时向客户端写入MyAntiForgeryCookie。

2. 修改JavaScript代码,正确获取请求令牌

替换原有的Cookie读取逻辑,从页面的隐藏input中获取请求令牌:

function create(successCallback) {
    let model = {
        client: appointmentClientService.data.client,
        address: appointmentClientService.data.address,
        animals: appointmentAnimalService.animals,
        deposit: vm.deposit
    };

    Object.assign(model, appointmentData);

    // 从页面隐藏input获取请求令牌
    const antiForgeryToken = document.querySelector('input[name="AntiforgeryFieldname"]').value;
    const headers = {
        'X-CSRF-TOKEN': antiForgeryToken
    };

    vm.requestPending = true;
    $http({
        method: 'POST',
        url: '/api/appointment/public',
        data: model,
        headers: headers
    })
    .then(function (response) {
        toastr.success('Appointment created.');
        clearWindowUnloadCheck();

        printPaperwork(response.data.ids, function () {
            successCallback(response.data);
        });
    })
    .catch(function (response) {
        clinichq.helpers.showErrorMessage(response);
        vm.requestPending = false;
    });
}

3. 验证Cookie安全策略适配环境

你配置了CookieSecurePolicy.Always,这要求请求必须通过HTTPS发送,否则浏览器不会携带Cookie:

  • 开发环境可临时调整为SameAsRequest方便测试:
options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
  • 生产环境必须使用HTTPS。

4. 检查SameSite Cookie配置(跨域场景)

如果前端与API部署在不同域名下,需调整Cookie的SameSite属性:

options.Cookie.SameSite = SameSiteMode.None;

注意:SameSiteMode.None必须配合SecurePolicy.Always使用,否则浏览器会拒绝该Cookie。

5. 确认Anti-Forgery属性配置无冲突

你同时在全局过滤器和控制器上添加了AutoValidateAntiforgeryTokenAttribute,这不会导致冲突,但需确保没有其他过滤器(如自定义授权过滤器)覆盖了验证逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:07:44