【问题标题】:Authorization token can not be forwarded into server side correctly授权令牌无法正确转发到服务器端
【发布时间】:2020-01-09 19:49:32
【问题描述】:

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

我发现请求已经发送了两次,第一个没有 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;
  }

【问题讨论】:

  • 您的第一个请求可能是在客户端地址与 API 地址不匹配时使用的 OPTIONS 调用,以检查 CORS 策略。这是浏览器发出的,与Angular本身无关。
  • 是的,第一个请求是 OPTIONS 请求。我已经在服务器端允许了 OPTIONS 请求,但没有进行身份验证。

标签: angular header authorization token httpclient


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我终于找到了重复请求的原因。第一个请求是 CORS 选项请求。这就是它不包含授权标头的原因。

    【讨论】:

      猜你喜欢
      • 2015-05-04
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      • 2014-07-09
      • 1970-01-01
      • 2021-07-28
      相关资源
      最近更新 更多