English
The interceptor and the guards
Step 1. The interceptor
Why. Every API call except the anonymous auth endpoints needs Authorization: Bearer <token>. Adding the header in every service method would repeat the same line forty times and forget it once. An interceptor sits in the pipeline of HttpClient, like an ASP.NET Core middleware or a DelegatingHandler: it sees every request on the way out and every response on the way back.
The interceptor also handles the expired token. The proactive timer of AuthService makes it rare, but a laptop that slept for an hour wakes up with a dead token. Then the API answers 401, and the interceptor refreshes once and repeats the request. The user notices nothing.
Do. Create the interceptor:
ts
import { HttpErrorResponse, HttpInterceptorFn, HttpRequest } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, from, switchMap, throwError } from 'rxjs';
import { AuthService } from './auth.service';
/** Auth routes that don't take a bearer token (the refresh cookie is enough, or nothing is). */
const ANONYMOUS = [
'/api/auth/register',
'/api/auth/login',
'/api/auth/refresh',
'/api/auth/logout',
];
function withToken(req: HttpRequest<unknown>, token: string | null): HttpRequest<unknown> {
return token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}` } }) : req;
}
/**
* Adds the bearer token to /api calls and sends cookies to /api/auth. On a 401 it refreshes the
* session once and retries; if that fails the user is signed out.
*/
export const authInterceptor: HttpInterceptorFn = (req, next) => {
if (!req.url.startsWith('/api/')) {
return next(req);
}
if (req.url.startsWith('/api/auth/')) {
req = req.clone({ withCredentials: true });
}
if (ANONYMOUS.includes(req.url)) {
return next(req);
}
const auth = inject(AuthService);
const router = inject(Router);
const sentToken = auth.accessToken();
return next(withToken(req, sentToken)).pipe(
catchError((error: unknown) => {
if (!(error instanceof HttpErrorResponse) || error.status !== 401) {
return throwError(() => error);
}
// Another request may already have refreshed the session while this one was in flight.
const current = auth.accessToken();
const retryToken =
current && current !== sentToken ? Promise.resolve(current) : auth.refresh();
return from(retryToken).pipe(
switchMap((token) => {
if (!token) {
auth.endSession(router.url);
return throwError(() => error);
}
return next(withToken(req, token));
}),
);
}),
);
};- A function, not a class.
HttpInterceptorFnis(req, next) => Observable<HttpEvent>.inject()works inside it because Angular runs interceptors in an injection context. Class-based interceptors (HTTP_INTERCEPTORS) still exist but need more ceremony. - Only
/api/calls are touched; a request to another host or to a static file never gets the token. withCredentials: truefor/api/auth/— the auth endpoints read and write the refresh cookie. Through the proxy the calls are same-origin and the browser would send the cookie anyway; the flag keeps it working if the API ever lives on another origin.ANONYMOUSendpoints get no token:registerandloginhave none yet,refreshandlogoutwork with the cookie. A token on them would not hurt, but a 401 from them must not trigger a refresh —refreshrefreshing itself would loop.- Requests are immutable.
req.clone({ setHeaders: … })returns a new request; the original is never changed. - On 401 the interceptor compares the token it sent with the current one. If another request has refreshed in the meantime, the current token is already new and is used at once; otherwise it calls the single-flight
auth.refresh().from(promise)turns the Promise into an Observable, andswitchMapreplaces the failed response with the retried request. - No loop. The retry calls
next(...), the rest of the pipeline after this interceptor, notHttpClientagain. If the retried request gets a 401 too, the error simply goes to the caller. - A failed refresh means the session is gone:
endSession(router.url)sends the user to the sign-in page and remembers where they were.
RxJS operators in one paragraph
observable.pipe(op1, op2) builds a new Observable from an old one, like LINQ's method chain builds a new sequence. catchError(fn) replaces an error with another Observable (here: the retry), throwError(() => error) is an Observable that only fails, and switchMap(fn) maps each value to a new Observable and continues with that one. Topics 17 and 18 add debounceTime, distinctUntilChanged and filter.
Test it:
ts
import {
HttpClient,
HttpErrorResponse,
provideHttpClient,
withInterceptors,
} from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { ME, settle } from '../../../testing/fakes';
import { authInterceptor } from './auth.interceptor';
import { AuthService } from './auth.service';
const response = (token: string) => ({
accessToken: token,
accessTokenExpiresAt: new Date(Date.now() + 15 * 60_000).toISOString(),
user: ME,
});
describe('authInterceptor', () => {
let http: HttpClient;
let backend: HttpTestingController;
let auth: AuthService;
beforeEach(async () => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(withInterceptors([authInterceptor])),
provideHttpClientTesting(),
provideRouter([{ path: '**', children: [] }]),
],
});
http = TestBed.inject(HttpClient);
backend = TestBed.inject(HttpTestingController);
auth = TestBed.inject(AuthService);
const login = auth.login({ login: 'alice', password: 'x' });
backend.expectOne('/api/auth/login').flush(response('token-1'));
await login;
});
afterEach(() => backend.verify());
it('adds the bearer token to API calls', async () => {
const result = firstValueFrom(http.get('/api/me'));
const req = backend.expectOne('/api/me');
expect(req.request.headers.get('Authorization')).toBe('Bearer token-1');
req.flush(ME);
await result;
});
it('leaves anonymous auth calls alone but sends cookies', async () => {
const result = firstValueFrom(http.post('/api/auth/refresh', null));
const req = backend.expectOne('/api/auth/refresh');
expect(req.request.headers.has('Authorization')).toBe(false);
expect(req.request.withCredentials).toBe(true);
req.flush(response('token-2'));
await result;
});
it('does not touch requests outside /api', async () => {
const result = firstValueFrom(http.get('/assets/x.json'));
const req = backend.expectOne('/assets/x.json');
expect(req.request.headers.has('Authorization')).toBe(false);
req.flush({});
await result;
});
it('refreshes once on 401 and retries with the new token', async () => {
const result = firstValueFrom(http.get('/api/chats'));
backend.expectOne('/api/chats').flush(null, { status: 401, statusText: 'Unauthorized' });
await settle();
backend.expectOne('/api/auth/refresh').flush(response('token-2'));
await settle();
const retry = backend.expectOne('/api/chats');
expect(retry.request.headers.get('Authorization')).toBe('Bearer token-2');
retry.flush({ items: [] });
expect(await result).toEqual({ items: [] });
});
it('signs out when the refresh fails', async () => {
const result = firstValueFrom(http.get('/api/chats'));
backend.expectOne('/api/chats').flush(null, { status: 401, statusText: 'Unauthorized' });
await settle();
backend.expectOne('/api/auth/refresh').flush(null, { status: 401, statusText: 'Unauthorized' });
await expect(result).rejects.toBeInstanceOf(HttpErrorResponse);
expect(auth.isAuthenticated()).toBe(false);
});
it('does not loop when the retried request is rejected again', async () => {
const result = firstValueFrom(http.get('/api/chats'));
backend.expectOne('/api/chats').flush(null, { status: 401, statusText: 'Unauthorized' });
await settle();
backend.expectOne('/api/auth/refresh').flush(response('token-2'));
await settle();
backend.expectOne('/api/chats').flush(null, { status: 401, statusText: 'Unauthorized' });
await expect(result).rejects.toMatchObject({ status: 401 });
backend.expectNone('/api/auth/refresh');
});
});provideHttpClient(withInterceptors([authInterceptor]))builds the same pipeline as the application.beforeEachsigns in through the realAuthService, so every test starts with the tokentoken-1.- The retry tests answer the first request with 401, let the interceptor's promise run (
await settle()), answer the refresh, and check that the repeated request carriestoken-2. - "does not loop" answers the retry with 401 again and asserts with
expectNonethat no second refresh was attempted.
Step 2. The guards
Why. Most pages make sense only for a signed-in user, and the sign-in and registration pages only for a guest. A guard runs before the router activates a route and either lets it through or redirects. It is a UX feature, not security: the API checks the token on every request whatever the client shows.
Do. Create the guards. The routes of topic 17 use them.
ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
/** Pages that need a session. The session is restored by an app initializer before routing. */
export const authGuard: CanActivateFn = (_route, state) => {
const auth = inject(AuthService);
if (auth.isAuthenticated()) {
return true;
}
return inject(Router).createUrlTree(['/login'], {
queryParams: state.url && state.url !== '/' ? { returnUrl: state.url } : undefined,
});
};
/** Sign-in and register pages: signed-in users go straight to their chats. */
export const guestGuard: CanActivateFn = () =>
inject(AuthService).isAuthenticated() ? inject(Router).createUrlTree(['/chats']) : true;CanActivateFnis a function that returnstrueto allow the navigation, or aUrlTreeto redirect. Returning aUrlTreeis better than callingrouter.navigateinside the guard: the router cancels the current navigation and starts the new one cleanly.authGuardkeeps the requested URL in?returnUrl=, so after signing in the user lands where they wanted to go.- The guards are synchronous. They can be, because the session is restored before the first navigation — the next step.
Step 3. Restoring the session at start-up
Why. When the page loads, the router immediately matches the URL and runs the guards. If restoreSession() were still waiting for the API, authGuard would see a guest and redirect a signed-in user to /login. An app initializer is a function that Angular runs — and, if it returns a Promise, awaits — before it starts the router.
Do. Replace the generated app.config.ts with its final version:
ts
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import {
ApplicationConfig,
inject,
provideAppInitializer,
provideBrowserGlobalErrorListeners,
} from '@angular/core';
import { provideRouter, withComponentInputBinding, withRouterConfig } from '@angular/router';
import { routes } from './app.routes';
import { authInterceptor } from './core/auth/auth.interceptor';
import { AuthService } from './core/auth/auth.service';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideHttpClient(withInterceptors([authInterceptor])),
provideRouter(
routes,
withComponentInputBinding(),
// chats/:chatId/info reads :chatId from its parent route.
withRouterConfig({ paramsInheritanceStrategy: 'always' }),
),
// Turn the refresh cookie into a session before the first navigation runs the guards.
provideAppInitializer(() => inject(AuthService).restoreSession()),
],
};provideHttpClient(withInterceptors([authInterceptor]))puts the interceptor into the pipeline of everyHttpClientin the application.withComponentInputBinding()lets the router set route parameters and query parameters as component inputs: a page declareschatId = input.required<string>()and receives:chatId(topics 17 and 19).paramsInheritanceStrategy: 'always'makes parameters of parent routes visible to child routes; the chat info panel of topic 21, atchats/:chatId/info, reads:chatIdfrom its parent. Current Angular versions use'always'by default (older ones used'emptyOnly'); the explicit setting documents that the panel relies on it.provideAppInitializer(() => inject(AuthService).restoreSession())runs the refresh once at start-up and waits for it.restoreSessionnever throws, so a visitor without a cookie simply starts signed out.
Check
powershell
npm test -- --watch=false Test Files 4 passed (4)
Tests 19 passed (19)Start the API and the client (./Run.ps1 api, ./Run.ps1 web) and open http://localhost:4200 with the developer tools' Network tab open. Exactly one request goes out on each load: POST /api/auth/refresh, answered 401 Unauthorized, because there is no session yet. The page stays empty; topic 17 adds the sign-in page.