fix(auth): centralize token handling in auth service (#1534)
This commit is contained in:
@@ -10,8 +10,7 @@ import { AuthInterceptorService } from './auth-interceptor.service';
|
||||
describe('AuthInterceptorService', () => {
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
internalRefreshToken: vi.fn<() => Observable<{ accessToken: string; refreshToken: string }>>(),
|
||||
saveInternalTokens: vi.fn<(accessToken: string, refreshToken: string) => void>(),
|
||||
ensureAccessToken: vi.fn<(options?: {forceRefresh?: boolean}) => Observable<string>>(),
|
||||
logout: vi.fn<() => void>(),
|
||||
};
|
||||
|
||||
@@ -21,8 +20,7 @@ describe('AuthInterceptorService', () => {
|
||||
beforeEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
authService.internalRefreshToken.mockReset();
|
||||
authService.saveInternalTokens.mockReset();
|
||||
authService.ensureAccessToken.mockReset();
|
||||
authService.logout.mockReset();
|
||||
|
||||
TestBed.resetTestingModule();
|
||||
@@ -82,7 +80,7 @@ describe('AuthInterceptorService', () => {
|
||||
|
||||
it('retries a 401 request after a successful refresh', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(of({ accessToken: 'fresh-token', refreshToken: 'refresh-token' }));
|
||||
authService.ensureAccessToken.mockReturnValue(of('fresh-token'));
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
@@ -97,34 +95,47 @@ describe('AuthInterceptorService', () => {
|
||||
next
|
||||
));
|
||||
|
||||
expect(authService.internalRefreshToken).toHaveBeenCalledOnce();
|
||||
expect(authService.saveInternalTokens).toHaveBeenCalledWith('fresh-token', 'refresh-token');
|
||||
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
|
||||
expect((response as HttpResponse<string>).body).toBe('Bearer fresh-token');
|
||||
});
|
||||
|
||||
it('retries a 401 request without persisting tokens when the refresh response is incomplete', async () => {
|
||||
it('logs out when AuthService cannot refresh a complete token pair', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(of({ accessToken: 'fresh-token', refreshToken: '' }));
|
||||
authService.ensureAccessToken.mockReturnValue(throwError(() => new Error('Authentication response did not include a complete token pair')));
|
||||
const next = vi.fn(() => throwError(() => new HttpErrorResponse({ status: 401 })));
|
||||
|
||||
await expect(firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
))).rejects.toBeInstanceOf(Error);
|
||||
|
||||
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
|
||||
expect(authService.logout).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not log out when the retried request fails after refresh succeeds', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.ensureAccessToken.mockReturnValue(of('fresh-token'));
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
if (request.headers.get('Authorization') === 'Bearer fresh-token') {
|
||||
return of(new HttpResponse({ status: 200, body: request.headers.get('Authorization') }));
|
||||
return throwError(() => new HttpErrorResponse({ status: 500 }));
|
||||
}
|
||||
return throwError(() => new HttpErrorResponse({ status: 401 }));
|
||||
});
|
||||
|
||||
const response = await firstValueFrom(interceptor(
|
||||
await expect(firstValueFrom(interceptor(
|
||||
new HttpRequest('GET', `${apiUrl}/books`),
|
||||
next
|
||||
));
|
||||
))).rejects.toBeInstanceOf(HttpErrorResponse);
|
||||
|
||||
expect(authService.saveInternalTokens).not.toHaveBeenCalled();
|
||||
expect((response as HttpResponse<string>).body).toBe('Bearer fresh-token');
|
||||
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
|
||||
expect(authService.logout).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('logs out when the refresh request fails', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
authService.internalRefreshToken.mockReturnValue(
|
||||
authService.ensureAccessToken.mockReturnValue(
|
||||
throwError(() => new HttpErrorResponse({ status: 500 }))
|
||||
);
|
||||
|
||||
@@ -147,14 +158,14 @@ describe('AuthInterceptorService', () => {
|
||||
next
|
||||
))).rejects.toBeInstanceOf(HttpErrorResponse);
|
||||
|
||||
expect(authService.internalRefreshToken).not.toHaveBeenCalled();
|
||||
expect(authService.ensureAccessToken).not.toHaveBeenCalled();
|
||||
expect(authService.logout).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('queues concurrent 401s behind a single refresh operation', async () => {
|
||||
it('delegates concurrent 401 refresh coordination to AuthService', async () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('expired-token');
|
||||
const refreshSubject = new Subject<{ accessToken: string; refreshToken: string }>();
|
||||
authService.internalRefreshToken.mockReturnValue(refreshSubject.asObservable());
|
||||
const refreshSubject = new Subject<string>();
|
||||
authService.ensureAccessToken.mockReturnValue(refreshSubject.asObservable());
|
||||
|
||||
const next = vi.fn((request: HttpRequest<unknown>) => {
|
||||
const authHeader = request.headers.get('Authorization');
|
||||
@@ -167,12 +178,13 @@ describe('AuthInterceptorService', () => {
|
||||
const firstRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/books`), next));
|
||||
const secondRequest = firstValueFrom(interceptor(new HttpRequest('GET', `${apiUrl}/libraries`), next));
|
||||
|
||||
refreshSubject.next({ accessToken: 'refreshed-token', refreshToken: 'refresh-token' });
|
||||
refreshSubject.next('refreshed-token');
|
||||
refreshSubject.complete();
|
||||
|
||||
const [firstResponse, secondResponse] = await Promise.all([firstRequest, secondRequest]);
|
||||
|
||||
expect(authService.internalRefreshToken).toHaveBeenCalledOnce();
|
||||
expect(authService.ensureAccessToken).toHaveBeenCalledTimes(2);
|
||||
expect(authService.ensureAccessToken).toHaveBeenCalledWith({forceRefresh: true});
|
||||
expect((firstResponse as HttpResponse<string>).body).toBe('Bearer refreshed-token');
|
||||
expect((secondResponse as HttpResponse<string>).body).toBe('Bearer refreshed-token');
|
||||
});
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
import { HttpErrorResponse, HttpEvent, HttpHandlerFn, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
|
||||
import { inject } from '@angular/core';
|
||||
import { catchError, filter, switchMap, take } from 'rxjs/operators';
|
||||
import { BehaviorSubject, Observable, throwError, defer } from 'rxjs';
|
||||
import { catchError, switchMap } from 'rxjs/operators';
|
||||
import { Observable, throwError, defer } from 'rxjs';
|
||||
import { AuthService } from '../../shared/service/auth.service';
|
||||
import { API_CONFIG } from '../config/api-config';
|
||||
|
||||
let isRefreshing = false;
|
||||
const refreshTokenSubject = new BehaviorSubject<string | null>(null);
|
||||
|
||||
export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandlerFn) => {
|
||||
const authService = inject(AuthService);
|
||||
|
||||
@@ -42,36 +39,14 @@ export const AuthInterceptorService: HttpInterceptorFn = (req, next: HttpHandler
|
||||
|
||||
function handle401Error(authService: AuthService, request: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
|
||||
return defer(() => {
|
||||
if (!isRefreshing) {
|
||||
isRefreshing = true;
|
||||
refreshTokenSubject.next(null);
|
||||
|
||||
return authService.internalRefreshToken().pipe(
|
||||
switchMap(response => {
|
||||
isRefreshing = false;
|
||||
const { accessToken, refreshToken } = response;
|
||||
if (accessToken && refreshToken) {
|
||||
authService.saveInternalTokens(accessToken, refreshToken);
|
||||
refreshTokenSubject.next(accessToken);
|
||||
}
|
||||
return next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
||||
}));
|
||||
}),
|
||||
catchError(err => {
|
||||
isRefreshing = false;
|
||||
forceLogout(authService);
|
||||
return throwError(() => err);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
return refreshTokenSubject.pipe(
|
||||
filter(token => token !== null),
|
||||
take(1),
|
||||
switchMap(token =>
|
||||
return authService.ensureAccessToken({forceRefresh: true}).pipe(
|
||||
catchError(err => {
|
||||
forceLogout(authService);
|
||||
return throwError(() => err);
|
||||
}),
|
||||
switchMap(accessToken =>
|
||||
next(request.clone({
|
||||
setHeaders: { Authorization: `Bearer ${token}` }
|
||||
setHeaders: { Authorization: `Bearer ${accessToken}` }
|
||||
}))
|
||||
)
|
||||
);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import {TestBed} from '@angular/core/testing';
|
||||
import {ActivatedRouteSnapshot, Router, RouterStateSnapshot, UrlTree} from '@angular/router';
|
||||
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
|
||||
import {firstValueFrom, Observable, of} from 'rxjs';
|
||||
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {AuthGuard} from './auth.guard';
|
||||
import {AuthChildGuard, AuthGuard} from './auth.guard';
|
||||
|
||||
describe('AuthGuard', () => {
|
||||
const route = {} as ActivatedRouteSnapshot;
|
||||
@@ -14,8 +15,7 @@ describe('AuthGuard', () => {
|
||||
};
|
||||
|
||||
const authService = {
|
||||
getInternalAccessToken: vi.fn<() => string | null>(),
|
||||
getInternalAccessTokenExpiry: vi.fn<() => number | null>(),
|
||||
ensureAuthenticated: vi.fn(),
|
||||
getIsDefaultPassword: vi.fn<() => boolean>(),
|
||||
};
|
||||
|
||||
@@ -24,8 +24,7 @@ describe('AuthGuard', () => {
|
||||
localStorage.clear();
|
||||
router.createUrlTree.mockClear();
|
||||
router.navigate.mockClear();
|
||||
authService.getInternalAccessToken.mockReset();
|
||||
authService.getInternalAccessTokenExpiry.mockReset();
|
||||
authService.ensureAuthenticated.mockReset();
|
||||
authService.getIsDefaultPassword.mockReset();
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
@@ -40,45 +39,61 @@ describe('AuthGuard', () => {
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
it('allows navigation for a valid non-default-password token', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('bearer token');
|
||||
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() + 3600000);
|
||||
function runGuard(): Observable<unknown> {
|
||||
return TestBed.runInInjectionContext(() => AuthGuard(route, state)) as Observable<unknown>;
|
||||
}
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
it('allows navigation for an authenticated non-default-password session', async () => {
|
||||
authService.ensureAuthenticated.mockReturnValue(of(true));
|
||||
authService.getIsDefaultPassword.mockReturnValue(false);
|
||||
|
||||
const result = await firstValueFrom(runGuard());
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(authService.ensureAuthenticated).toHaveBeenCalledOnce();
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to login when there is no token', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue(null);
|
||||
it('redirects to login when the session cannot be authenticated', async () => {
|
||||
authService.ensureAuthenticated.mockReturnValue(of(false));
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('returns a login UrlTree for expired tokens', () => {
|
||||
localStorage.setItem('accessToken_Internal', 'stale-token');
|
||||
authService.getInternalAccessToken.mockReturnValue('stale-token');
|
||||
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() - 10000);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
const result = await firstValueFrom(runGuard());
|
||||
|
||||
expect(router.createUrlTree).toHaveBeenCalledWith(['/login']);
|
||||
expect(result).toEqual({commands: ['/login']});
|
||||
expect(localStorage.getItem('accessToken_Internal')).toBeNull();
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('redirects to the change-password flow for default-password tokens', () => {
|
||||
authService.getInternalAccessToken.mockReturnValue('bearer token');
|
||||
authService.getInternalAccessTokenExpiry.mockReturnValue(Date.now() + 3600000);
|
||||
it('allows navigation when AuthService refreshes an expired token', async () => {
|
||||
authService.ensureAuthenticated.mockReturnValue(of(true));
|
||||
authService.getIsDefaultPassword.mockReturnValue(false);
|
||||
|
||||
const result = await firstValueFrom(runGuard());
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(router.createUrlTree).not.toHaveBeenCalledWith(['/login']);
|
||||
});
|
||||
|
||||
it('redirects to the change-password flow for default-password sessions', async () => {
|
||||
authService.ensureAuthenticated.mockReturnValue(of(true));
|
||||
authService.getIsDefaultPassword.mockReturnValue(true);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() => AuthGuard(route, state));
|
||||
const result = await firstValueFrom(runGuard());
|
||||
|
||||
expect(result).toBe(false);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/change-password']);
|
||||
expect(router.createUrlTree).toHaveBeenCalledWith(['/change-password']);
|
||||
expect(result).toEqual({commands: ['/change-password']});
|
||||
expect(router.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the same authentication flow for child routes', async () => {
|
||||
authService.ensureAuthenticated.mockReturnValue(of(true));
|
||||
authService.getIsDefaultPassword.mockReturnValue(false);
|
||||
|
||||
const result = await firstValueFrom(
|
||||
TestBed.runInInjectionContext(() => AuthChildGuard(route, state)) as Observable<unknown>
|
||||
);
|
||||
|
||||
expect(result).toBe(true);
|
||||
expect(authService.ensureAuthenticated).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,38 +1,29 @@
|
||||
import {inject} from '@angular/core';
|
||||
import {ActivatedRouteSnapshot, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {ActivatedRouteSnapshot, CanActivateChildFn, CanActivateFn, Router, RouterStateSnapshot} from '@angular/router';
|
||||
import {AuthService} from '../../shared/service/auth.service';
|
||||
import {map} from 'rxjs/operators';
|
||||
|
||||
export const AuthGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
const authenticateRoute = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
void route;
|
||||
void state;
|
||||
const router = inject(Router);
|
||||
const authService = inject(AuthService);
|
||||
|
||||
const internalAccessToken = authService.getInternalAccessToken();
|
||||
|
||||
if (internalAccessToken) {
|
||||
try {
|
||||
const isDefaultPassword = authService.getIsDefaultPassword();
|
||||
const internalAccessTokenExpiry = authService.getInternalAccessTokenExpiry();
|
||||
|
||||
if (internalAccessTokenExpiry != null && internalAccessTokenExpiry < Date.now()) {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
return authService.ensureAuthenticated().pipe(
|
||||
map(isAuthenticated => {
|
||||
if (!isAuthenticated) {
|
||||
return router.createUrlTree(['/login']);
|
||||
}
|
||||
|
||||
const isDefaultPassword = authService.getIsDefaultPassword();
|
||||
if (isDefaultPassword) {
|
||||
router.navigate(['/change-password']);
|
||||
return false;
|
||||
return router.createUrlTree(['/change-password']);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch {
|
||||
localStorage.removeItem('accessToken_Internal');
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
router.navigate(['/login']);
|
||||
return false;
|
||||
})
|
||||
);
|
||||
};
|
||||
|
||||
export const AuthGuard: CanActivateFn = authenticateRoute;
|
||||
export const AuthChildGuard: CanActivateChildFn = authenticateRoute;
|
||||
|
||||
Reference in New Issue
Block a user