角度拦截器-如果刷新令牌拦截器失败,如何注销?

时间:2020-02-19 08:22:03

标签: javascript angular jwt interceptor

信息

如果正在获取401,我将创建一个拦截器以使用刷新令牌更新访问令牌。现在的工作流程如下:

发送请求>获取401>发送刷新请求>更新访问令牌>发送新请求

我目前正在使用诺言而不是可观察的东西。


问题

如果上一个请求失败,如何注销?

发送请求>获取401>发送刷新请求>更新访问令牌>发送新请求>失败>注销

我有一个简单的注销方法,但是找不到在拦截器中的位置。


代码

export class RefreshInterceptor implements HttpInterceptor {
    currentUser: User | null = null;
    private isRefreshing = false;
    private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
        null
    );

    constructor(private authenticationService: AuthenticationService) {
        this.authenticationService.currentUser.subscribe(
            user => (this.currentUser = user)
        );
    }

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(error => {
                // check if user is signed in
                if (!this.currentUser) {
                    return throwError(error);
                }

                // handle only 401 error
                if (error instanceof HttpErrorResponse && error.status === 401) {
                    return from(this.handle401Error(request, next));
                } else {
                    return throwError(error);
                }
            })
        );
    }

    /**
     * Adds the new access token as a bearer header to the request
     * @param request - the request
     * @param token - the new access token
     */
    private async addToken(request: HttpRequest<any>, token: string) {
        const currentUser = this.authenticationService.currentUserValue;

        if (currentUser && currentUser.accessToken) {
            return request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`
                }
            });
        }

        return request;
    }

    private async handle401Error(request: HttpRequest<any>, next: HttpHandler) {
        // check if it is currently refreshing or not
        if (!this.isRefreshing) {
            this.isRefreshing = true;
            this.refreshTokenSubject.next(null);

            // send refresh request
            const token = await this.authenticationService.getRefresh();

            // update bearer token
            const newRequest = await this.addToken(request, token);

            // update values for next request
            this.isRefreshing = false;
            this.refreshTokenSubject.next(token);
            return next.handle(newRequest).toPromise();
        } else {
            const token = this.refreshTokenSubject.value();
            const newRequest = await this.addToken(request, token);
            return next.handle(newRequest).toPromise();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我通过以下方法解决了此问题:

  1. 修改了传出的已更改请求的标头(添加了重试标头,以便以后可以识别它)。
  2. 为注销创建了新的拦截器
  3. 正在寻找带有重试标头的请求。退出该请求。

刷新令牌拦截器

if (currentUser && currentUser.accessToken) {
            return request.clone({
                setHeaders: {
                    Authorization: `Bearer ${token}`,
                    Retry: "true"
                }
            });
        }

注销拦截器

@Injectable()
export class LogoutInterceptor implements HttpInterceptor {
    constructor(private authenticationService: AuthenticationService) {}

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(error => {
                // handle only 401 error
                if (error instanceof HttpErrorResponse && error.status === 401) {
                    from(this.handleRequest(request));
                    return throwError(error);
                }

                return next.handle(request);
            })
        );
    }

    private async handleRequest(request: HttpRequest<any>) {
        const isRetriedRequest = request.headers.get("retry");

        if (isRetriedRequest) {
            await this.authenticationService.logout();
        }
    }
}