首页 文章

带有Angular 4的.NET CORE API - 交换了cookie令牌和请求令牌

提问于
浏览
3

尝试使用Angular和.NET CORE实现XSRF时,我不断收到此消息:“提供的防伪令牌验证失败.Cookie令牌和请求令牌已交换 . ”我在Angular和API中都配置了相同的cookie和 Headers 名称 . 有人有主意吗?

Process

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);
    }
    }

1 回答

  • 4

    我遇到了同样的问题,我想我发现了这个问题 . AddAntiforgery has to be different 中的 options.Cookie.Name 比您使用 context.Response.Cookies.Append 手动设置的cookie .

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

    您可以注意到开发人员工具的不同之处 .

    • 使用 options.Cookie.Name 生成的默认令牌标记为 http onlyHttpOnly = true

    • 使用 context.Response.Cookies.Append 的手动附加标记被标记为 HttpOnly = false

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

相关问题