Files
apf_portal/libs/feature/auth/src/lib/auth.service.ts
T
julien 0e4f0fc611
CI / check (push) Successful in 2m32s
CI / commits (push) Has been skipped
CI / scan (push) Successful in 1m17s
CI / a11y (push) Successful in 1m8s
CI / perf (push) Successful in 2m49s
fix(portal-shell): send withCredentials on /me so the session cookie crosses SPA→BFF in dev (#114)
## Summary

Manual smoke after PR #113 surfaced a dev-only bug: after `/auth/callback` the BFF correctly sets the `portal_session` cookie and redirects to the SPA, but the SPA's next call to `/api/auth/me` comes back **401 with no `cookie:` header at all**. The user lands "back at the portal" but the header still shows "Sign in".

**Root cause.** Angular's `HttpClient` via `withFetch()` inherits `fetch`'s default `credentials: 'same-origin'`. In dev, `localhost:4200` (SPA) → `localhost:3000` (BFF) is cross-origin (different ports), so the browser drops the session cookie on the way out. SameSite=Lax is a red herring: both URLs share the registrable domain, so the cookie is still same-site — what was missing was opting the fetch into credentials.

**Fix.** Per-call `withCredentials: true` on the /me request. Only /me needs cookies today; login/logout are full-page navigations through `window.location`, which the browser hydrates with cookies regardless. A global `HttpInterceptor` will be the right abstraction once other authenticated BFF endpoints exist — premature for one consumer.

**BFF side was already correct.** `enableCors({ credentials: true })` in `main.ts`. Nothing to change.

A new spec pins `withCredentials === true` on the /me request so a future refactor can't silently drop the flag and reintroduce the bug.

## Test plan

- [x] `pnpm nx test feature-auth` → **9/9 pass** (was 8 before; +1 spec pinning the credentials flag).
- [x] `pnpm nx test portal-shell` → **32/32 pass**.
- [x] `pnpm nx lint feature-auth portal-shell` → clean.
- [x] `pnpm nx build portal-shell` → clean.
- [ ] Manual smoke against the running BFF: anonymous landing → click "Sign in" → Entra → callback → SPA lands with avatar + display name in the header (the very last step that failed before this fix).

---------

Co-authored-by: Julien Gautier <julien.gautier@apf.asso.fr>
Reviewed-on: #114
2026-05-12 22:35:10 +02:00

126 lines
4.6 KiB
TypeScript

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable, computed, inject, signal } from '@angular/core';
import { firstValueFrom } from 'rxjs';
import { AUTH_BFF_BASE_URL, AUTH_NAVIGATOR } from './auth.config';
import type { AuthState, CurrentUser } from './auth.types';
/**
* SPA-side authentication state, sourced from the BFF's
* `GET /api/auth/me` (ADR-0009 / ADR-0010). Acts as the single point
* of truth for "is the user signed in?" — every consumer (header
* widget, future route guards, downstream API gates) reads from the
* `state` / `currentUser` signals.
*
* Auto-bootstraps on first injection: the constructor fires an
* unawaited `refresh()`, so consuming components see `{kind:
* 'loading'}` briefly, then either `authenticated` or `anonymous`.
*
* `login()` and `logout()` perform full-page navigations to the BFF
* routes — the SPA never holds tokens (per ADR-0009), so a browser
* redirect through the Entra round-trip is the canonical path.
*/
@Injectable({ providedIn: 'root' })
export class AuthService {
private readonly http = inject(HttpClient);
private readonly bffBaseUrl = inject(AUTH_BFF_BASE_URL);
private readonly navigate = inject(AUTH_NAVIGATOR);
private readonly _state = signal<AuthState>({ kind: 'loading' });
readonly state = this._state.asReadonly();
/**
* Convenience: the user payload when authenticated, `null`
* otherwise. Lets templates write `@if (currentUser(); as user)`
* without unwrapping the discriminated state by hand.
*/
readonly currentUser = computed<CurrentUser | null>(() => {
const s = this._state();
return s.kind === 'authenticated' ? s.user : null;
});
/** True only while the very first /me round-trip is in flight. */
readonly isLoading = computed(() => this._state().kind === 'loading');
constructor() {
// Fire-and-forget so the constructor stays synchronous —
// Angular DI runs `providedIn: 'root'` services on first inject,
// which happens during app boot; awaiting here would push the
// first render behind the network round-trip.
void this.refresh();
}
/**
* Re-fetch `/auth/me`. Called automatically on first injection;
* consumers can call it again to refresh after a flow that may
* have changed the session (login redirect return, MFA step-up).
* Resolves once the new state is committed.
*/
async refresh(): Promise<void> {
try {
// `withCredentials: true` is mandatory: the SPA at
// http://localhost:4200 calls the BFF at http://localhost:3000 —
// different origins, so `fetch`'s default `credentials:
// 'same-origin'` would drop the `__Host-portal_session` cookie
// and /me would always answer 401. Production (single origin
// behind the same edge) doesn't need it but it's harmless there.
// CORS on the BFF side already allows credentials
// (`apps/portal-bff/src/main.ts` → `enableCors({ credentials:
// true })`).
const user = await firstValueFrom(
this.http.get<CurrentUser>(this.meUrl, { withCredentials: true }),
);
this._state.set({ kind: 'authenticated', user });
} catch (err) {
this._state.set(toErrorState(err));
}
}
/**
* Initiate sign-in by navigating to the BFF's `/auth/login`. The
* BFF builds the Entra authorize URL and 302s the browser; the
* round-trip lands on `/auth/callback` which writes the session
* and redirects back to the SPA.
*
* The navigation goes through the injected {@link AUTH_NAVIGATOR}
* function — `window.location.assign` in production, a `vi.fn()`
* in specs.
*/
login(): void {
this.navigate(this.loginUrl);
}
/**
* Initiate sign-out by navigating to the BFF's `/auth/logout`,
* which destroys the session, clears the cookie, and 302s through
* Entra's RP-initiated logout — single sign-out per ADR-0009.
*/
logout(): void {
this.navigate(this.logoutUrl);
}
get meUrl(): string {
return `${this.bffBaseUrl}/auth/me`;
}
get loginUrl(): string {
return `${this.bffBaseUrl}/auth/login`;
}
get logoutUrl(): string {
return `${this.bffBaseUrl}/auth/logout`;
}
}
function toErrorState(err: unknown): AuthState {
// The BFF returns 401 with `{error: 'unauthenticated'}` when no
// session is on the request. Anything else (network failure,
// 5xx, malformed response) lands in the explicit `error` state so
// the UI can distinguish "please sign in" from "can't reach the
// server right now".
if (err instanceof HttpErrorResponse && err.status === 401) {
return { kind: 'anonymous' };
}
return { kind: 'error' };
}