我有一个具有这些属性的端点:
[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]")]
那它被禁用了,为什么?
答案 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 > ();