c# - 全局应用 IgnoreAntiforgeryTokenAttribute 不会禁用 ValidateAntiForgeryToken

标签 c# asp.net-core .net-core asp.net-core-mvc

我有一个具有这些属性的端点:

[HttpPost]
[ValidateAntiForgeryToken]
[Route("[controller]/[action]")]

当我全局应用IgnoreAntiforgeryTokenAttribute

.AddMvc(opts =>
{
    opts.Filters.Add(typeof(CustomExceptionFilter));
    opts.Filters.Add(new IgnoreAntiforgeryTokenAttribute());
    // or
    opts.Filters.Add(typeof(IgnoreAntiforgeryTokenAttribute));
})

它没有禁用该[ValidateAntiForgeryToken],但是当我做了类似的事情时:

[HttpPost]
[ValidateAntiForgeryToken]
[IgnoreAntiforgeryToken]
[Route("[controller]/[action]")]

然后就被禁用了,为什么?

最佳答案

对于内置的 ValidateAntiForgeryToken,您无法通过 Startup.cs 中的 IgnoreAntiforgeryTokenAttribute 禁用它。您可以引用Default order of execution

要解决此问题,您可以实现自己的 ValidateAntiforgeryTokenAuthorizationFilter,例如

public class CustomValidateAntiforgeryTokenAuthorizationFilter : ValidateAntiforgeryTokenAuthorizationFilter
{
    public CustomValidateAntiforgeryTokenAuthorizationFilter(IAntiforgery antiforgery, ILoggerFactory loggerFactory)
        :base(antiforgery, loggerFactory)
    {
    }
    protected override bool ShouldValidate(AuthorizationFilterContext context)
    {
        var filters = context.Filters;
        if (filters.Where(f => f.GetType() == typeof(IgnoreAntiforgeryTokenAttribute)) != null)
        {
            return false;
        }
        else
        {
            return base.ShouldValidate(context);
        }
    }
}

并通过 ValidateAntiforgeryTokenAuthorizationFilter 进行注册,例如

services.AddMvc(options => {
    options.Filters.Insert(0, new IgnoreAntiforgeryTokenAttribute());

    options.Filters.Add(typeof(WebApiExceptionFilter)); // by type
});
services.AddScoped<ValidateAntiforgeryTokenAuthorizationFilter, CustomValidateAntiforgeryTokenAuthorizationFilter > ();

关于c# - 全局应用 IgnoreAntiforgeryTokenAttribute 不会禁用 ValidateAntiForgeryToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56187976/

相关文章:

c# - .Net Core 身份框架通过声明获取用户

c# - ASP.NET VNext 调试 MVC 源代码

c# - 在 EF 上下文中使用 appsettings.json 配置

c# - .NET Core 运行时向后兼容性

具有默认值参数的 c# 重载(扩展)函数

c# - 这里发生了什么? (.Net) GC.CollectionCount(0) 不断增加

c# - Newtonsoft.JSON 序列化产生一个具有对象类型的唯一字符串

sql-server - 使用 SQL Management Studio 连接到 Linux (docker) 上的 SQL Server

.net - .net core mvc 中 session 超时时如何重定向

c# - ASP.Net Core WebApi 中的非属性路由