如何编写获取和添加令牌的 HttpInterceptor?

How do I write an HttpInterceptor that gets and adds a token?

我正在使用 Angular 6 和 RxJs 6.5.2。我终其一生都无法弄清楚链接可观察对象以向 HTTP 请求添加访问令牌的语法,以及 return 满足拦截方法所需的类型。我已经尝试了订阅、管道、映射的所有排列...

  private getApiToken(): Observable<any> {
    // TODO load from configuration
    return this.httpClient.post("https://localhost:1234/connect/token",
      {
        grant_type: "client_credentials",
        client_id: "MyClient",
        client_secret: "MySecret",
        scope: "ApiScope"
      });
  }


  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   // how do I call getApiToken here?
   return next.handle(req);
  }

请注意,如果我能正常工作,我当然会缓存令牌。

为了链接这些,你可以这样做

 private getApiToken(): Observable<any> {
    // TODO load from configuration
    return this.httpClient.post("https://localhost:1234/connect/token",
      {
        grant_type: "client_credentials",
        client_id: "MyClient",
        client_secret: "MySecret",
        scope: "ApiScope"
      });
  }


  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return this.getApiToken()
     .pipe(concatMap((token) => next.handle(req)));
  }

但是您将不得不对令牌进行一些操作。这是我从我的一个工作应用程序中获得的模式。

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
   return this.getApiToken()
     .pipe(
       concatMap((token) => {
        let headers = {
          'Authorization': `Bearer ${token}`,
        };

        const dupReq = request.clone({
            setHeaders: headers,
        });

        return next.handle(dupReq);
       }),
     );
  }

希望对您的请求有所帮助。

也就是说,我建议您在应用程序启动时获取令牌,而不是等到发出请求。我见过的通常模式是获取令牌作为登录的一部分,在登录期间保存它,如果登录则获取令牌并添加到请求中,如果没有则不添加令牌并假定它是未经授权的请求。