Angular 7自动刷新承载令牌

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

我有一个AuthService,本质上有两种方法:

  • getAuthToken(返回Promise,因此可以延迟调用/多次调用,并且在单个集合上有阻塞等待)

  • refreshToken(还返回一个Promise,使用原始JWT上可用的刷新令牌来请求新的身份验证令牌)

我想自动

  • 将承载令牌应用于每个http请求(正在工作)
  • 刷新刷新令牌-我快到了,除了带有刷新令牌的请求结果不会使它返回给原始订阅者。

这里是代码:

import { HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from "@angular/common/http";
import { from, Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { AuthService } from "./auth.service";

@Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
  constructor(
    private _authService: AuthService,
  ) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return from(this.addBearerToken(req, next));
  }

  private async addBearerToken(req: HttpRequest<any>, next: HttpHandler): Promise<HttpEvent<any>> {
    const token = await this._authService.getAuthToken();

    const headerSettings = req.headers.keys().reduce(
      (acc, cur) => {
        acc[cur] = req.headers.getAll(cur);
        return acc;
      }, {});

    if (token) {
      headerSettings["Authorization"] = `Bearer ${ token }`;
    } else {
      console.log("performing request without auth!");
    }
    // prevent 302 redirect to challenge on a 401
    headerSettings["X-Requested-With"] = "XMLHttpRequest";
    const
      headers = new HttpHeaders(headerSettings),
      newRequest = req.clone({ headers });
    const result = next.handle(newRequest).toPromise();
    result.catch(async (err) => {
      if (err.status === 401) {
        const
          newToken = await this._authService.refreshToken();
        headerSettings["Authorization"] = `Bearer ${ newToken }`;
        const
          updatedHeaders = new HttpHeaders(headerSettings),
          updatedRequest = req.clone({ headers: updatedHeaders });
        console.log("requery with new token"); // <-- I see this when I have a 401, eg by altering the auth token to be bad, whilst leaving the refresh token alone
        return next.handle(updatedRequest).toPromise().then(data => {
          console.log("requeried data:", data); // <-- I also see this fire, with the valid data coming back from the second request
          return data; // <-- however the original caller doesn't get this data
        });
      }
    });
    return result;

  }
}

我必须假设这可能是由于我混合了Observables和Promises(之所以这样做,是因为AuthService是异步的,使用Promises)。另外,如果没有401,则原始呼叫会正确通过-就像在该行之后删除了promise链一样]

next.handle(newRequest).toPromise();

我想念什么?

我有一个AuthService,本质上有两种方法:getAuthToken(返回Promise,因此可以通过对单个集合的阻塞等待来延迟调用/多次调用)refreshToken(还返回...

angular authorization jwt interceptor bearer-token
1个回答
3
投票

您在这里打破了束缚:

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