我正在使用操作筛选器来发送请求令牌。 只需将其应用于您想要新防伪令牌的操作,例如Angular2 SPA,的WebAPI动作等
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class AngularAntiForgeryTokenAttribute : ActionFilterAttribute
{
private const string CookieName = "XSRF-TOKEN";
private readonly IAntiforgery antiforgery;
public AngularAntiForgeryTokenAttribute(IAntiforgery antiforgery)
{
this.antiforgery = antiforgery;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
base.OnResultExecuting(context);
if (!context.Cancel)
{
var tokens = antiforgery.GetAndStoreTokens(context.HttpContext);
context.HttpContext.Response.Cookies.Append(
CookieName,
tokens.RequestToken,
new CookieOptions { HttpOnly = false });
}
}
}
/* HomeController */
[ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]
public IActionResult Index()
{
return View();
}
/* AccountController */
[HttpPost()]
[AllowAnonymous]
[ValidateAntiForgeryToken]
// Send new antiforgery token
[ServiceFilter(typeof(AngularAntiForgeryTokenAttribute), IsReusable = true)]
public async Task<IActionResult> Register([FromBody] RegisterViewModel model)
{
//...
return Json(new { });
}
注册在启动属性,并配置防伪服务读取请求令牌形式 “X-XSRF-TOKEN” 报头。
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddScoped<AngularAntiForgeryTokenAttribute>();
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
}
}
我遵循上述步骤,但我得到400错误的请求错误。我的“发布”请求发送到服务器作为“选项:方法类型。我问了一个关于这个问题的问题 - https://stackoverflow.com/questions/44841588/antiforgery-token-implementation-in-angular-2-and- web-api-using-aps-net-core –
我今天发现的一些其他信息 - 如果您在IIS中托管,则应在服务器上配置Data Protection以保留用于生成AntiForgeryToken的密钥。 ,应用程序重新启动时令牌将变为无效。有关如何配置的信息,请参阅此处 - https://docs.microsoft.com/en-us/aspnet/core/publishing/iis#data-protection – DanO