Full answer
Security in a single-page app has three separate topics.
CSRF (cross-site request forgery): a malicious site makes the user's browser send a request to your API, and the browser attaches cookies automatically. If you authenticate with cookies, you need protection:
- Angular's built-in support is the double-submit cookie pattern. The server sets a cookie (default name
XSRF-TOKEN, readable by JavaScript). For mutating requests (anything but GET and HEAD) to relative URLs or the same origin,HttpClientcopies the cookie value into theX-XSRF-TOKENheader. The server compares them. Another site cannot read your cookie, so it cannot add the header. - Customise names with
withXsrfConfiguration({ cookieName, headerName }), or disable it withwithNoXsrfProtection()when you use tokens only. - Add
SameSite=LaxorStricton session cookies as a second layer. Angular does not add the header to requests to other origins. - If you authenticate with a bearer token in a header, the browser does not add it automatically, so classic CSRF does not apply. XSS becomes the main risk.
CSP (Content Security Policy): a response header that lists allowed sources for scripts and styles. Aim for script-src 'nonce-...' 'strict-dynamic' and no unsafe-inline. Angular adds inline styles at run time, so give it the nonce: put ngCspNonce="<nonce>" on the root element (the server sets a fresh random value per response) or provide CSP_NONCE. With the application builder you can also enable autoCsp in build options (v19+, experimental) to generate a hash-based policy.
Token storage:
- Best: server-managed session or tokens in
HttpOnly; Secure; SameSitecookies (BFF pattern). JavaScript cannot read them, so XSS cannot steal them, and you need CSRF protection. - If you must hold a token in JavaScript, keep it in memory (lost on refresh, refreshed silently), not in
localStorage, which any injected script can read. - Use short-lived access tokens and refresh rotation.
Interceptor rule: attach the Authorization header only to your API origin. Sending it to every URL leaks tokens to third parties, such as analytics or image hosts.
Defence in depth: keep Angular's sanitisation on, never use bypassSecurityTrust* on user input, and avoid innerHTML with untrusted data (see the XSS item).
// file: security.config.ts
import { HttpInterceptorFn, provideHttpClient, withInterceptors, withXsrfConfiguration } from '@angular/common/http';
import { ApplicationConfig, CSP_NONCE } from '@angular/core';
export const API_ORIGIN = 'https://api.example.com';
let accessToken: string | null = null; // memory only: never localStorage
export function setAccessToken(token: string | null): void {
accessToken = token;
}
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const isApi = req.url.startsWith(`${API_ORIGIN}/`);
if (!isApi || !accessToken) {
return next(req);
}
return next(req.clone({ setHeaders: { Authorization: `Bearer ${accessToken}` } }));
};
function readNonce(): string | null {
return document.querySelector('app-root')?.getAttribute('ngCspNonce') ?? null;
}
export const securityConfig: ApplicationConfig = {
providers: [
provideHttpClient(
withXsrfConfiguration({ cookieName: 'XSRF-TOKEN', headerName: 'X-XSRF-TOKEN' }),
withInterceptors([authInterceptor]),
),
// Only needed if the server sends a nonce but you cannot use the ngCspNonce attribute.
{ provide: CSP_NONCE, useFactory: readNonce },
],
};
// file: security.config.spec.ts
import { HttpClient, provideHttpClient, withInterceptors, withXsrfConfiguration } from '@angular/common/http';
import { PlatformLocation } from '@angular/common';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { API_ORIGIN, authInterceptor, setAccessToken } from './security.config';
describe('http security', () => {
let http: HttpClient;
let backend: HttpTestingController;
beforeEach(() => {
document.cookie = 'XSRF-TOKEN=abc123; path=/';
TestBed.configureTestingModule({
providers: [
provideHttpClient(withXsrfConfiguration({}), withInterceptors([authInterceptor])),
provideHttpClientTesting(),
// The test platform's mock location has no real origin (its href is "//"), and the XSRF
// interceptor skips requests when it cannot work out the origin. Give it one.
{ provide: PlatformLocation, useValue: { href: 'http://localhost:4200/' } },
],
});
http = TestBed.inject(HttpClient);
backend = TestBed.inject(HttpTestingController);
setAccessToken('token-1');
});
afterEach(() => {
document.cookie = 'XSRF-TOKEN=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
setAccessToken(null);
backend.verify();
});
it('adds the XSRF header to a same-origin POST', () => {
http.post('/api/marks', {}).subscribe();
const req = backend.expectOne('/api/marks');
expect(req.request.headers.get('X-XSRF-TOKEN')).toBe('abc123');
req.flush({});
});
it('does not add the XSRF header to a GET', () => {
http.get('/api/marks').subscribe();
const req = backend.expectOne('/api/marks');
expect(req.request.headers.has('X-XSRF-TOKEN')).toBeFalse();
req.flush({});
});
it('sends the bearer token only to the API origin', () => {
http.get(`${API_ORIGIN}/marks`).subscribe();
http.get('https://cdn.example.net/logo.png').subscribe();
const api = backend.expectOne(`${API_ORIGIN}/marks`);
const cdn = backend.expectOne('https://cdn.example.net/logo.png');
expect(api.request.headers.get('Authorization')).toBe('Bearer token-1');
expect(cdn.request.headers.has('Authorization')).toBeFalse();
api.flush({});
cdn.flush('');
});
});Angular 20.3, strict check passes, and a Karma spec in headless Chrome checks that the XSRF header is added for a same-origin POST and that the token goes only to the API origin.
Key points
- Angular double-submit XSRF: cookie to header on mutating same-origin requests, checked by the server.
- CSP with nonces and `strict-dynamic`. Give Angular the nonce for its styles.
- Prefer `HttpOnly` cookies, or in-memory tokens. Avoid `localStorage` for tokens.
- Send bearer tokens only to your own API origin.
Common mistakes
- Disabling XSRF protection while using cookie sessions.
- Using `unsafe-inline` in the CSP because Angular styles were blocked, instead of providing a nonce.
- Adding the token header to every outgoing request, including third-party URLs.
- Testing XSRF without a valid location origin, so the interceptor silently adds nothing and the test passes only for the wrong reason.
Follow-ups
- Why does a bearer-token API not need CSRF protection, and what risk replaces it?
- How would you rotate and revoke refresh tokens?
- What is a backend-for-frontend, and how does it help?
Tips
- Separate the three topics at the start. It shows structure.
- Explain why the double-submit pattern works, in one sentence.
- Name the trade-off of cookies versus in-memory tokens.
Evaluation rubric
- Explains CSRF protection and Angular's built-in support correctly.
- Describes CSP nonces and Angular's role.
- Chooses token storage with reasons and scopes the interceptor.