授权令牌无法正确转发到服务器端

问题描述 投票:1回答:2

我实现了AuthTokenInterceptor,如下所示。我的问题是,授权令牌无法正确转发到服务器端。我确信在将请求传递到next.handler()之前,可以通过request.headers.get(“ Authorization”)获得身份验证令牌。

我发现请求已发送两次,第一个没有授权头,但是第二个有头。

我从管道中删除了重试,但是仍然有两个请求发送到服务器端。

我的项目有一个特殊情况。我使用了第三方i18n工具,它需要来自'@ angular / http'的旧HttpModule。因此,我同时导入了HttpModule和HttpClientModule。

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    if (this.authService.getAccessToken()) {
      request = this.addToken(request);
    }

    return next.handle(request).pipe(catchError(error => {
      if (error instanceof HttpErrorResponse 
        && ( error.status === 401 || error.status == 403) ) {
        if ( error.status == 401 )
          return this.handle401Error(error, request, next);
        else
          return this.handle403Error(error, request, next);
      } else {
        return throwError(error);
      }
    }));
  }

  private addToken(request: HttpRequest<any>): HttpRequest<any> {
    const tokenName = this.authService.getAuthorizationTokenName();
    const tokenValue = this.authService.getAuthorizationTokenValue();

    // Clone the request and replace the original headers with
    // cloned headers, updated with the authorization.
    const authReq = request.clone({
      headers: request.headers.set(tokenName, tokenValue)
    });
    return authReq;
  }

angular header authorization token httpclient
2个回答
0
投票

拦截器仅接收一个请求,但是有两个请求发送到服务器。


0
投票

我终于找到了双重要求的原因。第一个请求是CORS选项请求。这就是为什么它不包含Authorization标头的原因。

© www.soinside.com 2019 - 2024. All rights reserved.