【发布时间】:2018-06-10 20:40:06
【问题描述】:
我正在开发一个使用asp.net core2 和Angular 运行的网络API 应用程序。详细的开发环境配置为here。
我正在尝试配置AntiForgeryToken 验证,但它一直失败。我按照配置。 here,但我不得不修改它,因为我的 Angular 应用程序和 asp.net 服务器在两个不同的端口上运行,因为前端启动不会生成令牌。我通过在应用程序组件ngOnInit 上调用API 路径(/api/Account/ContactInitialization)来启动后端,这使我能够生成令牌。
配置如下图,
IServiceCollection服务:
services.AddAntiforgery(options =>
{
options.HeaderName = "X-CSRF-TOKEN";
options.SuppressXFrameOptionsHeader = false;
});
IApplicationBuilder Configure:
app.Use(next => context =>
{
string path = context.Request.Path.Value;
if (
string.Equals(path, "/", StringComparison.OrdinalIgnoreCase) ||
string.Equals(path, "/api/Account/ContactInitialization", StringComparison.OrdinalIgnoreCase) ||
string.Equals(path, "/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 });
}
return next(context);
});
asp.net。生成两组密钥,
我用[ValidateAntiForgeryToken] 修饰了我的方法,并在我的标头请求中包含了XSRF-TOKEN cookie 内容。但是我在拨打API 后一直收到400 (Bad Request) 回复!我在这里错过了什么?
控制器方法,
[Authorize]
[ValidateAntiForgeryToken]
[HttpPost]
public IEnumerable<string> AutherizeCookie()
{
return new string[] { "Hello", "Auth Cookie" };
}
我的详细标头请求如下所示,
【问题讨论】:
-
LGTM。尝试从中间件中删除
if条件? -
如果你的意思是生成令牌我没有问题,否则请解释为什么要删除条件
标签: c# asp.net-core-2.0 csrf-protection antiforgerytoken