我们在项目中使用 Asp .NET core 5.0 API 后端创建 Angular12 SPA。在这里,我们实现了用于验证的防伪 XSRF/CSRF 令牌。
XSRF 令牌通过添加请求标头来发送令牌和验证来工作。
为什么 XSRF 令牌也不适用于 HTML?(隐藏的 __RequestVerificationToken 值)
启动.cs
{
services.AddAntiforgery(options =>
{
// Set Cookie properties using CookieBuilder properties†.
options.FormFieldName = "AntiforgeryFieldname";
options.HeaderName = "X-XSRF-TOKEN";
options.SuppressXFrameOptionsHeader = false;
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IAntiforgery antiforgery)
{
app.Use(next => context =>
{
string path = context.Request.Path.Value;
if (path.ToLower().Contains("/api") || string.Equals(path, "/index.html", StringComparison.OrdinalIgnoreCase))
{
// The request token can be sent as a JavaScript-readable cookie,
// and Angular uses it by default.
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken,
new CookieOptions()
{
HttpOnly = false,
Path = "/",
Secure = true,
SameSite = SameSiteMode.Strict
});
}
return next(context);
});
}
//app.module.ts
HttpClientXsrfModule.withOptions({
cookieName: 'XSRF-TOKEN',
headerName: 'X-CSRF-TOKEN'
})
services.ts
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// load token
let xsrfToken = this.xsrfTokenExtractor.getToken();
if (xsrfToken != null) {
// create a copy of the request and
// append the XSRF token to the headers list
const authorizedRequest = req.clone({
withCredentials: true,
headers: req.headers.set('X-XSRF-TOKEN', xsrfToken)
});
return next.handle(authorizedRequest);
} else {
return next.handle(req);
}
}```