我不确定这里发生了什么,但我在我的cookie中看到了2个不同的令牌。一个是“XSRF-TOKEN”,另一个是“.AspNetCore.Antiforgery.OnvOIX6Mzn8”,它们有不同的值。
我正在使用ASP.Net Core 2.1,并设置了SPA(前端使用Angular),在Startup.cs中添加了以下内容。
我不知道是什么创建了后面的那个令牌,因为它似乎不是我添加的任何代码生成的。
我正在使用ASP.Net Core 2.1,并设置了SPA(前端使用Angular),在Startup.cs中添加了以下内容。
我不知道是什么创建了后面的那个令牌,因为它似乎不是我添加的任何代码生成的。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IAntiforgery antiforgery)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
context.Response.AddApplicationError(error.Error.Message);
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseJwtTokenMiddleware();
app.UseSpaStaticFiles();
app.UseCookiePolicy();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.UseSpaPrerendering(options =>
{
options.BootModulePath = $"{spa.Options.SourcePath}/dist/server/main.js";
options.BootModuleBuilder = env.IsDevelopment()
? new AngularCliBuilder(npmScript: "build:ssr")
: null;
options.ExcludeUrls = new[] { "/sockjs-node" };
});
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
app.UseMiddleware<AntiForgeryMiddleware>("XSRF-TOKEN");
}
}
public static class ApplicationBuilderExtensions
{
public static IApplicationBuilder UseAntiforgeryTokenMiddleware(this IApplicationBuilder builder, string requestTokenCookieName)
{
return builder.UseMiddleware<AntiForgeryMiddleware>(requestTokenCookieName);
}
}
public class AntiForgeryMiddleware
{
private readonly RequestDelegate next;
private readonly string requestTokenCookieName;
private readonly string[] httpVerbs = new string[] { "GET", "HEAD", "OPTIONS", "TRACE" };
public AntiForgeryMiddleware(RequestDelegate next, string requestTokenCookieName)
{
this.next = next;
this.requestTokenCookieName = requestTokenCookieName;
}
public async Task Invoke(HttpContext context, IAntiforgery antiforgery)
{
if (httpVerbs.Contains(context.Request.Method, StringComparer.OrdinalIgnoreCase))
{
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append(requestTokenCookieName, tokens.RequestToken, new CookieOptions()
{
HttpOnly = false
});
}
await next.Invoke(context);
}
}