【问题标题】:.net core - Anti-forgery Exception Handling.net core - 防伪异常处理
【发布时间】:2020-04-14 14:40:54
【问题描述】:

我正在尝试处理客户端上的防伪异常,我想向用户显示相关消息,但我从 .Net Core 服务器得到的只是 400 Bad Request 响应,所以我正在尝试用我自己的回复来覆盖它。

所以我添加了过滤器:

using Microsoft.AspNetCore.Mvc.Core.Infrastructure;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Website.Filters
{
    public class RedirectAntiforgeryValidationFailedResultFilter : IAlwaysRunResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is IAntiforgeryValidationFailedResult result)
            {
                [overraid response]
            }
        }

        public void OnResultExecuted(ResultExecutedContext context)
        {            
            if (context.Result is IAntiforgeryValidationFailedResult result)
            {
                [overraid response]
            }
        }
    }
}

在 startup.cs 上

services.AddAntiforgery(options =>
        {
                options.SuppressXFrameOptionsHeader = true;
                options.HeaderName = "......";
                options.Cookie.Name = ".....";
                options.Cookie.Path = "/";
                options.Cookie.Expiration = TimeSpan.FromDays(2);
       });

services.AddMvc(options =>
                options.Filters.Add<RedirectAntiforgeryValidationFailedResultFilter>()
                ).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

我正在使用此功能为用户设置防伪令牌

private static void SetToken(HttpContext context, IAntiforgery antiforgery)
{
    var tokens = antiforgery.GetAndStoreTokens(context);
    context.Response.Cookies.Append("....", tokens.RequestToken, new CookieOptions()
    {
        HttpOnly = false,
        Secure = true,
        MaxAge = TimeSpan.FromDays(2),
        SameSite = SameSiteMode.Strict
    });
}

我永远无法达到[覆盖响应]。

您可以在下图中看到结果是真正的 AntiforgeryValidationFailedResult 并且仍然无法进入条件。

【问题讨论】:

  • 我无法重现您的问题。它可能会成功进入覆盖响应。您能否分享更多有关您的 Startup.cs 和您的请求操作的信息?
  • @Rena 我更新了我的问题并添加了更多细节。

标签: c# .net asp.net-core antiforgerytoken


【解决方案1】:

当使用 [ApiController] 属性时,MVC 将错误结果(状态代码为 400 或更高的结果)转换为带有 ProblemDetails 的结果。 ProblemDetails 类型基于RFC 7807 specification,用于在 HTTP 响应中提供机器可读的错误详细信息。你可以阅读更多关于这个here的信息。

所以为了解决这个问题,我不得不抑制地图客户端错误。

services.AddMvc(options => 
                options.Filters.Add<RedirectAntiforgeryValidationFailedResultFilter>())
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
                .ConfigureApiBehaviorOptions(options =>
                {
                    options.SuppressMapClientErrors = true;
                });

【讨论】:

    猜你喜欢
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多