English
The session
Step 1. Where the tokens live
Why. Topic 8 issued two tokens and topic 13 put the refresh token into an HttpOnly cookie with Path=/api/auth and SameSite=Strict. JavaScript cannot read that cookie at all — a script injected by an attacker cannot steal it — and the browser sends it only to the auth endpoints. The access token comes in the JSON body of login, register and refresh, and the client must keep it somewhere to send it with every request.
Table 16.2. Where a web client can keep the access token
| Place | Survives a reload | Readable by an injected script | Chatex |
|---|---|---|---|
localStorage | yes | yes — stolen tokens stay valid for 15 minutes | no |
| a cookie | yes | not if HttpOnly, but then it is sent automatically, which needs CSRF protection | only for the refresh token |
| memory (a field of a service) | no | only while the page is open | yes |
Keeping the access token in memory loses it on every reload, and that is fine: at start-up the app calls POST /api/auth/refresh, the browser adds the cookie, and the API answers with a fresh access token and the user's profile. The session survives reloads through the cookie, not through storage.
Step 2. AuthService
Why. One service owns the session: who is signed in, the current access token, signing in and out, and renewing the token. The rest of the client reads the user from it and asks it for a token.
The delicate part is renewal. The API rotates the refresh token on every use and treats the reuse of an old one as theft: it revokes all sessions of the user (topic 8). If two requests notice an expired token at the same moment and both call refresh, the second call presents a token that the first call has just rotated — and the user is signed out on every device. Refreshing must therefore be single-flight: at most one refresh request at a time, shared by everyone who needs it.
Do. Create the service:
ts
import { Injectable, computed, inject, signal } from '@angular/core';
import { Router } from '@angular/router';
import { firstValueFrom } from 'rxjs';
import { AuthApi } from '../api/chatex-api';
import { AuthResponse, LoginRequest, MyProfileDto, RegisterRequest } from '../api/models';
/** Refresh this long before the access token expires. */
const REFRESH_AHEAD_MS = 60_000;
/** A token closer than this to expiry is refreshed before use. */
const MIN_TOKEN_LIFE_MS = 20_000;
/**
* Holds the session. The access token lives only in memory; the refresh token is an HttpOnly cookie
* the browser sends to /api/auth. Refreshing is single-flight: the server rotates the refresh token on
* every use and treats reuse of an old one as theft (it revokes every session), so two parallel
* refresh calls must never happen.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly api = inject(AuthApi);
private readonly router = inject(Router);
private readonly token = signal<string | null>(null);
private expiresAt = 0;
private refreshInFlight: Promise<string | null> | null = null;
private refreshTimer: ReturnType<typeof setTimeout> | undefined;
readonly user = signal<MyProfileDto | null>(null);
readonly isAuthenticated = computed(() => this.user() !== null && this.token() !== null);
/** Increases on every sign-out so other services can drop per-user caches. */
readonly sessionEpoch = signal(0);
accessToken(): string | null {
return this.token();
}
/** At startup: turn the refresh cookie (if any) into a session. Never throws. */
async restoreSession(): Promise<void> {
await this.refresh();
}
async login(body: LoginRequest): Promise<void> {
this.apply(await firstValueFrom(this.api.login(body)));
}
async register(body: RegisterRequest): Promise<void> {
this.apply(await firstValueFrom(this.api.register(body)));
}
/** Returns the new access token, or null (and signs out locally) when the session is gone. */
refresh(): Promise<string | null> {
this.refreshInFlight ??= this.doRefresh().finally(() => (this.refreshInFlight = null));
return this.refreshInFlight;
}
/** A token that is good for at least a few more seconds, refreshing when needed. */
async getValidToken(): Promise<string | null> {
const token = this.token();
if (token && this.expiresAt - Date.now() > MIN_TOKEN_LIFE_MS) {
return token;
}
return this.refresh();
}
async logout(): Promise<void> {
try {
await firstValueFrom(this.api.logout());
} catch {
// Signing out locally is what matters.
}
this.endSession();
}
async logoutAll(): Promise<void> {
await firstValueFrom(this.api.logoutAll());
this.endSession();
}
/** Clears the session and goes to the sign-in page (session expired, password changed, ...). */
endSession(returnUrl?: string): void {
this.clear();
void this.router.navigate(['/login'], {
queryParams: returnUrl && returnUrl !== '/' ? { returnUrl } : undefined,
});
}
setUser(user: MyProfileDto): void {
this.user.set(user);
}
private async doRefresh(): Promise<string | null> {
try {
const response = await firstValueFrom(this.api.refresh());
this.apply(response);
return response.accessToken;
} catch {
this.clear();
return null;
}
}
private apply(response: AuthResponse): void {
this.expiresAt = Date.parse(response.accessTokenExpiresAt);
this.token.set(response.accessToken);
this.user.set(response.user);
this.scheduleRefresh();
}
private scheduleRefresh(): void {
clearTimeout(this.refreshTimer);
const delay = Math.max(5_000, this.expiresAt - Date.now() - REFRESH_AHEAD_MS);
this.refreshTimer = setTimeout(() => void this.refresh(), delay);
}
private clear(): void {
clearTimeout(this.refreshTimer);
const hadSession = this.user() !== null;
this.token.set(null);
this.user.set(null);
this.expiresAt = 0;
if (hadSession) {
this.sessionEpoch.update((n) => n + 1);
}
}
}- State in signals.
tokenis private: only the service changes it, and others read it throughaccessToken().useris public and read-only by convention (onlysetUserwrites it, after a profile change in topic 21).isAuthenticatediscomputedfrom both, so guards and templates always see a consistent answer. sessionEpochcounts sign-outs. Services that cache per-user data — avatars in topic 18, the stores in topics 18–20 — read it in aneffectand clear their caches when it changes, so the next user of the same browser tab never sees the previous user's data.refresh()is the single flight in two lines.??=assigns only if the field isnullorundefined: the first caller startsdoRefresh()and stores the promise; every caller until it settles gets the same promise;finallyclears the field for the next refresh. Five parallel callers, one request (Fig. 16.2).doRefresh()never throws: a failed refresh — no cookie, an expired or revoked token, the server down — clears the session and returnsnull.restoreSession()is therefore safe to call at start-up for a visitor who has never signed in.- Proactive renewal.
apply()stores the expiry andscheduleRefresh()sets a timer for one minute before it (REFRESH_AHEAD_MS), but never sooner than 5 seconds. A user who keeps the app open gets a new token before the old one expires, and requests rarely meet a 401. getValidToken()returns the current token if it lives at least 20 more seconds, otherwise refreshes first. The SignalR connection (topic 20) uses it, because a WebSocket cannot be retried like an HTTP request.logout()tells the server to revoke the refresh token, but signs out locally even if that call fails;logoutAll()must reach the server, so it lets errors through to the caller.endSession(returnUrl)clears the session and navigates to/login, remembering where the user was. The interceptor calls it when a refresh fails.firstValueFrom(observable)turns the one-response Observable ofHttpClientinto a Promise, so the service can useasync/awaitlike C#.
Fig. 16.2. Two callers, one refresh request
setTimeout without zone.js
scheduleRefresh uses a plain setTimeout. In a zoneless application that is fine: the callback changes signals (token, user), and signals schedule the re-rendering of whatever reads them. With zone.js the timer would also have triggered a check of the whole component tree.
Step 3. Shared test data
Why. Many specs need the same things: a signed-in user, another user, messages with ids that sort like UUIDv7, and a way to let pending promises run. They go into one file outside src/app, excluded from the application build by tsconfig.app.json (topic 15).
Do. Create the fakes. Topic 20 adds a fake of the realtime service to this file.
ts
import { signal } from '@angular/core';
import { MessageDto, MyProfileDto, UserSummaryDto } from '../app/core/api/models';
export const ME: MyProfileDto = {
id: '00000000-0000-7000-8000-00000000000a',
userName: 'alice',
email: '[email protected]',
displayName: 'Alice',
bio: null,
hasAvatar: false,
createdAt: '2026-11-01T10:00:00Z',
};
export const BOB: UserSummaryDto = {
id: '00000000-0000-7000-8000-00000000000b',
userName: 'bob',
displayName: 'Bob',
hasAvatar: false,
};
export function fakeAuth(user: MyProfileDto | null = ME) {
return {
user: signal(user),
sessionEpoch: signal(0),
isAuthenticated: signal(!!user),
};
}
/** Message ids sort like the server's UUIDv7 ids: by the number given. */
export function messageId(n: number): string {
return `00000000-0000-7000-8000-${n.toString().padStart(12, '0')}`;
}
export function message(n: number, overrides: Partial<MessageDto> = {}): MessageDto {
return {
id: messageId(n),
chatId: 'chat-1',
sender: BOB,
body: `message ${n}`,
replyToMessageId: null,
createdAt: new Date(Date.UTC(2026, 10, 10, 12, 0, n)).toISOString(),
editedAt: null,
isDeleted: false,
attachments: [],
...overrides,
};
}
/** Lets pending promise callbacks (firstValueFrom, async/await) run. */
export function settle(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}MEandBOBuse ids in the UUIDv7 format, so they look like real ones.fakeAuth()stands in forAuthServicein the tests of the stores (topic 18): just the three signals they read.messageId(n)andmessage(n, overrides)build messages whose ids sort byn, like the server's time-ordered ids;Partial<MessageDto>lets a test change only the fields it cares about.settle()waits one macrotask (setTimeout(…, 0)), so thatthencallbacks and the code after anawaitthat are already scheduled get to run.
Step 4. Testing the session
Why. The session logic is exactly the kind of code that breaks quietly: two refreshes instead of one, a session that is not cleared, a token that is not reused. The tests replace the network with Angular's HttpTestingController, which records every request and lets the test answer it — the client-side counterpart of a fake HttpMessageHandler.
Do. Create the spec:
ts
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { provideRouter } from '@angular/router';
import { ME, settle } from '../../../testing/fakes';
import { AuthResponse } from '../api/models';
import { AuthService } from './auth.service';
function authResponse(token: string): AuthResponse {
return {
accessToken: token,
accessTokenExpiresAt: new Date(Date.now() + 15 * 60_000).toISOString(),
user: ME,
};
}
describe('AuthService', () => {
let auth: AuthService;
let http: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
provideRouter([{ path: '**', children: [] }]),
],
});
auth = TestBed.inject(AuthService);
http = TestBed.inject(HttpTestingController);
});
afterEach(() => http.verify());
it('restores the session from the refresh cookie', async () => {
const restored = auth.restoreSession();
http.expectOne({ method: 'POST', url: '/api/auth/refresh' }).flush(authResponse('t1'));
await restored;
expect(auth.isAuthenticated()).toBe(true);
expect(auth.user()?.userName).toBe('alice');
expect(auth.accessToken()).toBe('t1');
});
it('stays signed out when there is no session', async () => {
const restored = auth.restoreSession();
http
.expectOne('/api/auth/refresh')
.flush({ code: 'invalid_refresh_token' }, { status: 401, statusText: 'Unauthorized' });
await restored;
expect(auth.isAuthenticated()).toBe(false);
});
it('sends only one refresh request for parallel callers', async () => {
const first = auth.refresh();
const second = auth.refresh();
await settle();
http.expectOne('/api/auth/refresh').flush(authResponse('t2'));
expect(await first).toBe('t2');
expect(await second).toBe('t2');
});
it('clears the session when a refresh fails', async () => {
const login = auth.login({ login: 'alice', password: 'Passw0rd!' });
http.expectOne('/api/auth/login').flush(authResponse('t1'));
await login;
const epoch = auth.sessionEpoch();
const refreshed = auth.refresh();
http.expectOne('/api/auth/refresh').flush(null, { status: 401, statusText: 'Unauthorized' });
expect(await refreshed).toBeNull();
expect(auth.user()).toBeNull();
expect(auth.sessionEpoch()).toBe(epoch + 1);
});
it('reuses a fresh token instead of refreshing', async () => {
const login = auth.login({ login: 'alice', password: 'Passw0rd!' });
http.expectOne('/api/auth/login').flush(authResponse('t1'));
await login;
expect(await auth.getValidToken()).toBe('t1');
http.expectNone('/api/auth/refresh');
});
});provideHttpClientTesting()replaces the HTTP backend with the testing controller;provideRouterwith a catch-all route givesendSessionsomewhere to navigate.http.expectOne(...)asserts that exactly one request matching the URL (or method and URL) is pending and returns it;flush(body, { status })answers it. A 401 answer makesHttpClientfail, as a real server would.afterEach(() => http.verify())fails the test if any request was left unanswered — an accidental extra call cannot go unnoticed.- "sends only one refresh request for parallel callers" is the single-flight test: two calls, then
expectOne— two requests would fail it withExpected one matching request for criteria "Match URL: /api/auth/refresh", found 2 requests. - "clears the session when a refresh fails" also checks that
sessionEpochgrows by one.
Check
powershell
npm test -- --watch=false Test Files 3 passed (3)
Tests 13 passed (13)Try the single-flight test: replace ??= with = in refresh() and run the tests again. The test fails with the message above. Restore ??=.