简体   繁体   中英

Angular interceptor - how do I logout if refresh token interceptor fails?

Info

I am creating an interceptor to use my refresh token to update my access token if I get a 401. The workflow looks like this now:

Sends request > gets 401 > sends refresh request > updates access token > sends new request

I am currently working with promises instead of observables.


Question

How do I logout if the last request fails?

Sends request > gets 401 > sends refresh request > updates access token > sends new request > fails > log out

I have a simple method for logging out, but I cannot find where to put it within the interceptor.


Code

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();
        }
    }
}

I solved it with the following approach:

  1. Modified the header of the outgoing, changed request (added a retry header so that I could identify it later).
  2. Created a new interceptor for logout
  3. Looked for a request with the retry header. Signed that request out.

Refresh token interceptor

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

Logout interceptor

@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();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM