mirror of
https://github.com/booklore-app/booklore.git
synced 2026-12-04 20:52:18 +01:00
Prevent token refresh deadlocks
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
import {HttpErrorResponse, HttpHandlerFn, HttpRequest} from '@angular/common/http';
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {Subject, firstValueFrom, throwError} from 'rxjs';
|
||||
import {beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
import {AuthInterceptorService} from './auth-interceptor.service';
|
||||
|
||||
describe('AuthInterceptorService', () => {
|
||||
const getInternalAccessToken = vi.fn(() => 'expired-access-token');
|
||||
const internalRefreshToken = vi.fn();
|
||||
const saveInternalTokens = vi.fn();
|
||||
const forceLogout = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
TestBed.configureTestingModule({
|
||||
providers: [{
|
||||
provide: AuthService,
|
||||
useValue: {getInternalAccessToken, internalRefreshToken, saveInternalTokens, forceLogout}
|
||||
}]
|
||||
});
|
||||
});
|
||||
|
||||
it('does not retry a 401 response from the refresh endpoint', async () => {
|
||||
const request = new HttpRequest('POST', `${API_CONFIG.BASE_URL}/api/v1/auth/refresh`, null);
|
||||
const unauthorized = new HttpErrorResponse({status: 401});
|
||||
|
||||
const response = TestBed.runInInjectionContext(() =>
|
||||
AuthInterceptorService(request, () => throwError(() => unauthorized))
|
||||
);
|
||||
|
||||
await expect(firstValueFrom(response)).rejects.toBe(unauthorized);
|
||||
expect(internalRefreshToken).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fails every queued request when token refresh fails', async () => {
|
||||
const refreshResult = new Subject<{accessToken: string; refreshToken: string}>();
|
||||
internalRefreshToken.mockReturnValue(refreshResult);
|
||||
const unauthorized = new HttpErrorResponse({status: 401});
|
||||
const next: HttpHandlerFn = vi.fn(() => throwError(() => unauthorized));
|
||||
|
||||
const firstRequest = interceptProtectedRequest('/api/v1/books', next);
|
||||
const secondRequest = interceptProtectedRequest('/api/v1/users/me', next);
|
||||
const firstResult = firstValueFrom(firstRequest);
|
||||
const secondResult = firstValueFrom(secondRequest);
|
||||
|
||||
refreshResult.error(unauthorized);
|
||||
|
||||
await expect(firstResult).rejects.toBe(unauthorized);
|
||||
await expect(secondResult).rejects.toBe(unauthorized);
|
||||
expect(forceLogout).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
function interceptProtectedRequest(path: string, next: HttpHandlerFn) {
|
||||
const request = new HttpRequest('GET', `${API_CONFIG.BASE_URL}${path}`);
|
||||
return TestBed.runInInjectionContext(() => AuthInterceptorService(request, next));
|
||||
}
|
||||
});
|
||||
@@ -1,24 +1,23 @@
|
||||
import {HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest} from '@angular/common/http';
|
||||
import {inject} from '@angular/core';
|
||||
import {Router} from '@angular/router';
|
||||
import {catchError, filter, switchMap, take} from 'rxjs/operators';
|
||||
import {BehaviorSubject, Observable, throwError} from 'rxjs';
|
||||
import {catchError, switchMap, take} from 'rxjs/operators';
|
||||
import {Observable, ReplaySubject, throwError} from 'rxjs';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {API_CONFIG} from '../config/api-config';
|
||||
|
||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
||||
const authService = inject(AuthService);
|
||||
const router = inject(Router);
|
||||
|
||||
const token = authService.getInternalAccessToken();
|
||||
const isApiRequest = req.url.startsWith(`${API_CONFIG.BASE_URL}/api/`);
|
||||
const isRefreshRequest = req.url === `${API_CONFIG.BASE_URL}/api/v1/auth/refresh`;
|
||||
|
||||
const authReq = (token && isApiRequest) ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
|
||||
|
||||
return next(authReq).pipe(
|
||||
catchError((error: HttpErrorResponse) => {
|
||||
if (error.status === 401) {
|
||||
return handle401Error(authService, authReq, next, router);
|
||||
if (error.status === 401 && !isRefreshRequest) {
|
||||
return handle401Error(authService, authReq, next);
|
||||
}
|
||||
return throwError(() => error);
|
||||
})
|
||||
@@ -26,12 +25,12 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
};
|
||||
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
let refreshTokenSubject = new ReplaySubject<string>(1);
|
||||
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn, router: Router): Observable<HttpEvent<unknown>> {
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
|
||||
if (!isRefreshing) {
|
||||
isRefreshing = true;
|
||||
refreshTokenSubject.next(null);
|
||||
refreshTokenSubject = new ReplaySubject<string>(1);
|
||||
|
||||
return authService.internalRefreshToken().pipe(
|
||||
switchMap(response => {
|
||||
@@ -47,14 +46,14 @@ function handle401Error(authService: AuthService, request: HttpRequest<unknown>,
|
||||
}),
|
||||
catchError(err => {
|
||||
isRefreshing = false;
|
||||
forceLogout(authService, router);
|
||||
refreshTokenSubject.error(err);
|
||||
authService.forceLogout('session_expired');
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap(token =>
|
||||
next(request.clone({
|
||||
@@ -63,7 +62,3 @@ function handle401Error(authService: AuthService, request: HttpRequest<unknown>,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function forceLogout(authService: AuthService, router: Router): void {
|
||||
authService.logout();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user