我在 Startup.cs 中设置了我的网络核心应用程序和防伪 middlweare:
services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");
在ConfigureServices方法中,以及
app.UseAntiForgeryMiddleware();
在配置方法中。
防伪中间件:
public class AntiForgeryMiddleware
{
private readonly IAntiforgery antiforgery;
private readonly AntiforgeryOptions options;
private readonly RequestDelegate next;
public AntiForgeryMiddleware(RequestDelegate next, IAntiforgery antiforgery, IOptions<AntiforgeryOptions> options)
{
this.next = next;
this.antiforgery = antiforgery;
this.options = options.Value;
}
public async Task Invoke(HttpContext context)
{
try
{
if (string.Equals(context.Request.Path.Value, "/", StringComparison.OrdinalIgnoreCase) ||
string.Equals(context.Request.Path.Value, "/index.html", StringComparison.OrdinalIgnoreCase))
{
// We can send the request token as a JavaScript-readable cookie, and Angular will use it by default.
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions() { HttpOnly = false });
}
if (string.Equals("POST", context.Request.Method, StringComparison.OrdinalIgnoreCase))
{
await antiforgery.ValidateRequestAsync(context);
context.Response.StatusCode = 204;
}
}
catch (Exception ex)
{
throw ex;
}
await next(context);
}
}
I use
[ValidateAntiForgeryToken]
在我的控制器操作上。
如何设置 angular2 post 请求来发送与 net core 应用程序匹配的 x-xsrf-token 标头?