我想在 Angular 项目中使用 AntiForge Token
后端我也用ASP.NET Core写过
中间件代码是
if (path != null)
{
var tokens = _antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append(
key: "XSRF-TOKEN",
value: tokens.RequestToken,
options: new CookieOptions
{
Path="/",
HttpOnly = false // Now JavaScript is able to read the cookie
});
}
return _next(context);
\\startup
app.UseAntiforgeryToken();
services.AddAntiforgery(x => x.HeaderName = "X-XSRF-TOKEN");
但是如果我使用 ValidateAntiForgeryToken 会发生什么,我的函数不会运行,因为 XSRF-TOKEN cookie 没有发送给它。
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
return this._httpClient.post(environment.authUrl+ 'api/Account/login',credentials,{headers: headers }).pipe(
switchMap((response: any) => {
// Store the access token in the local storage
this.accessToken = response.access_token;
this.refreshToken = response.refresh_token;
// Set the authenticated flag to true
this._authenticated = true;
//Store the user on the user service
this._userService.user = response.user;
// Return a new observable with the response
return of(response);
})
);
我查看的时候发现第一次请求的时候返回了XSRF-TOKEN cookies,但是没有保存在浏览器中
有一点,如果我直接调用 API 而不是使用 Ajax,则此令牌将保存在浏览器中。
此后,令牌将存储在cookie中,但不会在请求中发送XSRF-TOKEN
environment.authUrl
是绝对路径吗?根据 Angular 的源代码,绝对路径被 HttpClientXsrfModule 上的 Angular 代码显式忽略。请改成相对路径
此外,它还必须满足一些其他条件。详情可以查看this Angular Github issue.