4

尝试使用 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);
    }
    }
4

1 回答 1

7

我遇到了同样的问题,我想我找到了问题。options.Cookie.Name中的必须AddAntiforgery 您使用手动设置的 cookie不同context.Response.Cookies.Append

尝试更改其中一个的名称,它将起作用。现在,您覆盖使用options.Cookie.Name名称和tokens.RequestToken值的生成 cookie。

您可以注意到开发人员工具中的差异。

  • 使用生成的默认令牌options.Cookie.Name标记为http only( HttpOnly = true)
  • 使用的手动附加令牌context.Response.Cookies.Append标记为HttpOnly = false

第二个是从 JS/Angular 读取的(您可以在 JS 中读取它,因为HttpOnly=falseand 作为 ajax 请求中的标头发送,并针对无法从 JS 读取的默认值进行验证)

于 2018-04-21T08:19:45.767 回答