全局应用的IgnoreAntiforgeryTokenAttribute不会禁用ValidateAntiForgeryToken

时间:2019-05-17 13:58:44

标签: 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]")]

那它被禁用了,为什么?

2 个答案:

答案 0 :(得分:1)

尝试将过滤器插入列表的顶部,使它优先于现有过滤器,例如AutoValidateAntiforgeryTokenAttribute

opts.Filters.Insert(0, new IgnoreAntiforgeryTokenAttribute());

答案 1 :(得分:1)

对于内置ValidateAntiForgeryToken,您无法通过IgnoreAntiforgeryTokenAttribute中的Startup.cs禁用它。您可以引用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 > ();