私はアクションフィルタを使用してリクエストトークンを送信しています。 新しい偽造防止トークンが必要なアクションに単に適用します。など
[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 { });
}
Angular2 SPA、WebAPIのアクションは、スタートアップ内の属性を登録し、リクエストトークン形式 "X-XSRF-TOKEN" ヘッダを読み取ることAntiforgeryサービスを設定します。
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddScoped<AngularAntiForgeryTokenAttribute>();
services.AddAntiforgery(options =>
{
options.HeaderName = "X-XSRF-TOKEN";
});
}
}
上記の手順に従いましたが、400の不正なリクエストエラーが発生しています。私の "post"リクエストは "options:method type"としてサーバーに送られます。この問題に関する1つの質問 - https://stackoverflow.com/questions/44841588/antiforgery-token-implementation-in-angular-2-and- web-api-using-aps-net-core –
私が今日発見したいくつかの追加情報 - IISでホストしている場合は、AntiForgeryTokenを生成するために使用するキーを維持するために、サーバー上でデータ保護を設定する必要があります。 、アプリケーションが再起動するとトークンが無効になります。設定方法についてはこちらを参照してください - https://docs.microsoft.com/en-us/aspnet/core/publishing/iis#data-protection – DanO