首页 > 解决方案 > 在 Angular 10 中获取新的访问令牌后订阅未执行

问题描述

我已经在 API中使用access-token和机制进行身份验证。refresh-token当我的访问令牌过期时,我401 Unauthorized在 API 中遇到错误。所以我正在调用请求,它使用正常工作的刷新令牌返回新的访问令牌。但问题是.subscribe函数内部编写的代码没有被重新执行。

getActivePlan() {
    this.myPlanExplainerActive = true;
    var route = this.router.url;
    this.ps.getUserPlan().subscribe(res => {    <========== Getting 401 Unauthorized error when accss-token expired
      var plans = res.data.plans; <===== After getting new access-token execution never goes inside.
      var activeplan = plans.find(i => i.plan.isActive == true);
      if (activeplan != undefined) {
        this.activePlanId = activeplan.plan.planId;
        if (route != "/planparser/new-pdf-upload" && this.activePlanId != '') {
          this.router.navigate(['planparser/view-plan/', this.activePlanId]);
        }
      }
      else {
        this.router.navigate(['planparser/new-pdf-upload/']);
      }
    });
  }

在这里,当我在 getUserPlan() API 中收到 401 Unauthorized 错误时,我的拦截器会命中并获取新的访问令牌。但是,执行永远不会进入订阅内部,因此进一步的代码不会被执行。

intercept(request: HttpRequest<unknown>, next: HttpHandler):
        Observable<HttpEvent<unknown>> {
        let clonedRequest = request.clone();
        if (request.url.indexOf("/auth/oauth/token") == -1) {
            const auth = this.inject.get(AuthService);
            let cloned;
            if (auth.getToken()) {
                cloned = request.clone({
                    setHeaders: {
                        Authorization: `Bearer ${auth.getToken()}`,
                        'Accept': 'application/json'
                    }
                });
            }
            else {
                cloned = request.clone();
            }
            return next.handle(cloned).pipe(
                catchError(
                    (async (error: HttpErrorResponse) => {
                        if (error.status === 401) {
                            return this.handle401Error(request, next);
                        } else {
                            return throwError(error);
                        }
                    })
                )
            ) as any;
        }
        else if (request.url.indexOf('/auth/oauth/token') != -1) {
            clonedRequest = request.clone({
                setHeaders: {
                    Authorization: `Basic ${window.btoa('ClientId' + ':' + 'secret')}`,
                    'Content-Type': "application/x-www-form-urlencoded"
                }
            });
        }
        return next.handle(clonedRequest)
            .pipe(
                catchError(
                    ((error: HttpErrorResponse) => {
                        if (error.status !== 401) {
                            this.msgs.sendMessage({ command: 'Sorry, we are unable to process your plan. Please upload your correct NDIS plan PDF again.' });
                        }
                        return throwError(error);
                    })
                )
            );
    }

    private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
        if (!this.isRefreshingToken) {
            this.isRefreshingToken = true;
            this.tokenSubject.next(null);

            return this.authService.refreshTokenAPIcall().pipe(
                switchMap((token: any) => {
                    this.isRefreshingToken = false;
                    this.tokenSubject.next(token.access_token); <============== getting new token
                    return next.handle(this.addToken(request))
                })).subscribe(res => {
                    console.log(res);
                });

        } else {
            return this.tokenSubject.pipe(
                filter(token => token != null),
                take(1),
                switchMap(jwt => {
                    return next.handle(this.addToken(request));
                }));
        }
    }

在此处输入图像描述

标签: angularjwtaccess-tokenangular-http-interceptorsrefresh-token

解决方案


推荐阅读