尝试使用 Angular 和 .NET CORE 实现 XSRF 时,我不断收到此消息:“验证提供的防伪令牌失败。cookie 令牌和请求令牌已交换。” 我在 Angular 和 API 中配置了相同的 cookie 和标头名称。有人有想法么?
过程
Angular 对该 API 方法进行初始调用以检索 cookie
[HttpGet("startSession")]
public async Task<IActionResult> StartSession()
{
AntiforgeryTokenSet tokens = this.antiForgery.GetAndStoreTokens(this.HttpContext);
this.HttpContext.Response.Cookies.Append(this.options.Value.Cookie.Name, tokens.RequestToken, new CookieOptions { HttpOnly = false });
return this.Ok(
new
{
Success = true
});
}
然后 Angular 拦截下一个 POST 请求并稍微覆盖默认的 XSRF 处理,因为我需要它来处理 HTTPS URL
// Override default Angular XSRF handling since it won't work for
absolute URLs and we have to prefix with "https://"
// Source:https://github.com/angular/angular/blob/master/packages/common/http/src/xsrf.ts
@Injectable()
export class HchbHttpXsrfInterceptor implements HttpInterceptor {
constructor(
private tokenService: HttpXsrfTokenExtractor) {}
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const headerName = 'X-XSRF-TOKEN';
const lcUrl = req.url.toLowerCase();
// Skip both non-mutating requests.
// Non-mutating requests don't require a token
// anyway as the cookie set
// on our origin is not the same as the token expected by another origin.
if (req.method === 'GET' || req.method === 'HEAD' ) {
return next.handle(req);
}
const token = this.tokenService.getToken();
// Be careful not to overwrite an existing header of the same name.
if (token !== null && !req.headers.has(headerName)) {
req = req.clone({headers: req.headers.set(headerName, token)});
}
return next.handle(req);
}
}