我已通过以下方式实现了带有角度SPA和.net核心的防伪令牌,
.net代码
services.AddAntiforgery(options =>
{
options.SuppressXFrameOptionsHeader = true;
options.HeaderName = "X-XSRF-TOKEN";
options.Cookie.Name = "Anti-forgery-Cookie";
options.Cookie.Path = "/";
options.Cookie.Expiration = TimeSpan.FromDays(2);
});
中间件
string path = context.Request.Path.Value;
if (path != null && !path.ToLower().Contains("/api"))
{
var tokens = antiforgery.GetAndStoreTokens(context);
context.Response.Cookies.Append("XSRF-TOKEN",
tokens.RequestToken, new CookieOptions
{
HttpOnly = false,
Secure = true
}
);
}
角度拦截器
export class XsrfInterceptor implements HttpInterceptor {
constructor(private tokenExtractor: HttpXsrfTokenExtractor) { }
private actions: string[] = ['POST', 'PUT', 'DELETE', 'GET'];
private forbiddenActions: string[] = ['HEAD', 'OPTIONS'];
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = this.tokenExtractor.getToken();
const permitted = this.findByActionName(request.method, this.actions);
const forbidden = this.findByActionName(request.method, this.forbiddenActions);
if (permitted !== undefined && forbidden === undefined && token !== null) {
request = request.clone({ setHeaders: { 'X-XSRF-TOKEN': token } });
}
return next.handle(request);
}
private findByActionName(name: string, actions: string[]): string {
return actions.find(action => action.toLocaleLowerCase() === name.toLocaleLowerCase());
}
}
,我面临2个问题:
每个非API请求(例如/main.js /logo.png)都将替换防伪令牌。
反伪造不会在导航上刷新,例如,如果我在路径/ logIn上输入我的网站,我会看到反伪造令牌正在更新,但是在同一会话中导航到/ home时该防伪令牌未更新,并且我的API请求失败。
在Visual Studio的输出中,我看到了此错误:提供的防伪令牌是针对与当前用户不同的基于声明的用户
Angular版本8.1
dot-net核心版本2.2