【发布时间】:2018-07-12 18:55:22
【问题描述】:
我不确定这里发生了什么,但我在我的 cookie 中看到了 2 个不同的标记。一个是“XSRF-TOKEN”,一个是“.AspNetCore.Antiforgery.OnvOIX6Mzn8”,它们的值不同。
我正在使用 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);
}
}
【问题讨论】:
-
我没有使用表单标签助手。我在最初的帖子中没有提到它,但我已经更新它说它有一个 Angular SPA,并且它是预渲染的。我不使用 Razor。
标签: asp.net-mvc asp.net-core asp.net-core-mvc