当我试图用.NET内核实现XSRF时,我一直收到这样的消息:“对提供的防伪令牌的验证失败了。cookie令牌和请求令牌被交换了。”我在角和API中配置了相同的cookie和标头名称。有人有什么想法吗?
过程
对此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
});
}然后角截取下一个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);
}
}发布于 2018-04-21 08:19:45
我遇到了同样的问题,我想我发现了这个问题。options.Cookie.Name在AddAntiforgery 中必须与使用context.Response.Cookies.Append手动设置的cookie不同。
试着改变其中一个的名字,它就能工作了。现在,您将覆盖生成的cookie,该cookie使用options.Cookie.Name名称和tokens.RequestToken值。
您可以注意到开发工具的不同之处。
options.Cookie.Name生成的默认令牌被标记为http only (HttpOnly = true)context.Response.Cookies.Append手动附加的令牌标记为HttpOnly = false。第二种是从JS/Angular中读取(您可以在JS中读取它,因为HttpOnly=false作为头发送到ajax请求中,并根据无法从JS读取的默认消息进行验证)
https://stackoverflow.com/questions/49410813
复制相似问题