【问题标题】:How to call server api decorated with ValidateAntiForgeryToken using Httpclientfactory Typed clients?如何使用 Httpclientfactory Typed 客户端调用装饰有 ValidateAntiForgeryToken 的服务器 api?
【发布时间】:2021-10-27 17:55:34
【问题描述】:

我正在尝试使用输入的 httpclient 合并使用 GetAsync 和 PostAsync 的编辑表单页面。除了我的代码不使用 ValidateAntiForgeryToken 调用 API 操作外,一切正常。大多数在线示例都没有解决 httpclientfactory 使用的 httpcontent,而是使用 httpresponse。我知道我的请求中缺少防伪令牌。如何将其附加到请求标头?如何从视图中检索它?我想尽可能少地使用 Javascript。这是我的 Post 请求服务的 sn-p。 编辑:对于它的价值,我的 api 是 dot net core 而客户端是 dot net core mvc。

var response = await _httpclient.PostAsync("api/edit/" + id, httpcontent);
response.EnsureSuccessStatusCode(); ```

【问题讨论】:

  • 您是否遇到实际错误?你能详细说明一下服务器的响应吗?

标签: asp.net asp.net-core .net-core httpclient x-xsrf-token


【解决方案1】:

在MVC Edit视图页面中,它会使用一个隐藏文件(名为__RequestVerificationToken)来存储ValidateAntiForgeryToken,你可以使用F12开发者工具来查看它。

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">

修改数据后,您可以使用JQuery 获取更新后的数据,然后使用JQuery ajax 调用带有ValidateAntiForgeryToken 的API 方法。您可以参考my reply中的示例代码:

如果我们在 Startup.ConfigureServices 中自定义防伪选项,例如:自定义 RequestVerificationToken 的 Header Name。

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");  //configure the antiforgery service to look for the X-CSRF-TOKEN header. To prevent the cross-site request forgery.

然后,我们可以使用以下脚本:

        $.ajax({
            type: "POST",
            url: "/Survey/Create",
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: { "CategoryName": $("#CategoryName").val(), "CategoryID": $("#CategoryID").val() },
            success: function (response) {
                alert(response);
            },
            failure: function (response) {
                alert(response.responseText);
            },
            error: function (response) {
                alert(response.responseText);
            }
        });

另外,您也可以参考Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2011-12-06
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多