JWT and Session Security in Node.js and Angular: 8 Mistakes and a Safe Reference Setup
Algorithm pinning, weak secrets, unchecked claims, tokens in localStorage, no revocation, refresh tokens without rotation and cookies without CSRF protection: the JWT mistakes that matter in a Node.js and Angular app, plus a reference setup with httpOnly cookies.

For an Angular app talking to your own Node.js API, the safest default is not to let JavaScript touch the token at all. Send a short-lived access token and a rotating refresh token in HttpOnly, Secure cookies, pin the signing algorithm and check iss, aud and exp on every request, keep a way to revoke, and add CSRF protection because cookies are now in play. OWASP's session management cheat sheet says not to store authentication tokens, session IDs, JWTs or refresh tokens in localStorage or sessionStorage, because any script on the origin can read them. In August 2026 the IETF published RFC 10017, a best current practice for browser-based OAuth apps, which ranks a Backend for Frontend that keeps tokens out of the browser first.
Below are the eight mistakes I would look for in a review, each with the source that backs it, followed by a reference setup with working code. A JWT is a signed message and not a session. If you have one Angular app and one API, a server-side session with an opaque ID in an HttpOnly cookie is a perfectly good answer and is revoked by deleting a row. JWTs earn their complexity when several services must verify a token without calling a central one.
Mistake 1: not pinning the algorithm
RFC 8725, the JWT best current practice, says libraries must let the caller specify the set of supported algorithms and that each key must be used with exactly one algorithm. That prevents the classic confusion attack, where a token signed with HMAC using a public RSA key as the secret is accepted by a verifier that believes the header. The jsonwebtoken README says that if you omit algorithms in verify, defaults are chosen by the type of key you pass (HS256, HS384 and HS512 for a secret, the RS and ES families for public keys). That is a mitigation, not a policy, so always pass the list yourself. OWASP adds that you should make sure "alg":"none" is not accepted, and notes that recent implementations disable it by default.
Mistake 2: a weak signing secret
OWASP's JWT cheat sheet says an HMAC secret must have at least 160 bits of entropy, must not be a password, and should be at least as long as the HMAC output, which is 256 bits for HS256. Generate it, do not type it:
node -e "console.log(require('node:crypto').randomBytes(32).toString('base64url'))"
Store the result in an environment variable or a secrets manager, never in the repository, and rotate it if a build machine could have read it. Note that rotating the secret signs every user out. That is the intended effect.
Mistake 3: checking the signature but not the claims
The README says the payload returned by verify should be treated like any other user input, and that decode does not verify the signature and must not be used on untrusted messages. RFC 8725 asks you to validate the issuer and subject, and to use and validate an audience claim when tokens are issued for more than one service. In jsonwebtoken that means passing issuer and audience to verify, and letting exp do its work. A role claim is a convenience for the UI. For anything destructive, load the user and check their current permissions.
Mistake 4: keeping tokens in localStorage
This is the mistake behind most "JWT stolen" stories. OWASP's HTML5 security cheat sheet puts it in one sentence: a single cross-site scripting bug can be used to steal all the data in local storage. An HttpOnly cookie cannot be read by script, though MDN notes that the browser still sends it with JavaScript-initiated requests, so it limits theft but does not stop an attacker who already runs code in your page from making requests as the user. It also means you must now think about CSRF, which is mistake 7. For anything handling personal data, RFC 10017 goes further and strongly recommends the Backend for Frontend pattern, where the server holds the tokens in a cookie-based session and the browser never receives them. It requires Secure and HttpOnly on those cookies and recommends SameSite=Strict and CSRF protection in the BFF. The RFC is written for OAuth, but the storage reasoning applies to your own login as well.
Mistake 5: no way to revoke
A signed token is valid until it expires, wherever it is. OWASP's JWT cheat sheet says that without revocation you need a deny list, warns that storing the raw JWT or a hash of it is not safe because of token malleability, and suggests keying the list on jti and iss, together with a short expiry. Two practical options work well in a MongoDB app. Keep access tokens to ten minutes or so, and add a tv (token version) claim that you compare with a counter on the user document, so a password change or "sign out everywhere" increments the counter and kills every older token. The admin API behind this site uses that second approach with a single httpOnly cookie, and its two-factor sign-in is described in TOTP two-factor auth for a Node admin.
Mistake 6: refresh tokens that never rotate
RFC 9700, the OAuth 2.0 security best current practice, says refresh tokens for public clients must be sender-constrained or use refresh token rotation. With rotation the server issues a new refresh token on every refresh and invalidates the old one. If a stolen token and the real client both use it, one of them presents an already-used token, which tells the server something is wrong. The RFC's response is to revoke the currently active refresh token, which forces the legitimate user to sign in again.
Mistake 7: cookies without CSRF protection
Once the browser attaches credentials automatically, a malicious site can trigger requests to your API. OWASP's session management cheat sheet wants SameSite=Strict (preferred) or Lax on session cookies, and its CSRF cheat sheet calls SameSite a defence in depth that does not replace a proper CSRF defence in most deployments. Angular's HttpClient has the cookie-to-header half built in: it reads a cookie named XSRF-TOKEN and sends its value in an X-XSRF-TOKEN header on mutating requests, such as POST, to relative and same-origin URLs. The server must set that cookie and check the header, or the protection does nothing. withXsrfConfiguration renames them and withNoXsrfProtection turns the feature off. Keep it on, and keep Angular patched: the 2026 advisory CVE-2026-111753 leaked the token to cross-origin hosts through a URL parsing discrepancy, and is fixed in 20.3.34, 21.0.3 and all 22.x releases (the version table is in Patching a MEAN Stack).
Mistake 8: treating the payload as private
The payload of a signed token is only encoded, not encrypted, so anyone who holds it can read it. Do not put email addresses, internal notes or anything you would not print in a log. You can see this for yourself in my JWT decoder, which decodes a token in the browser without checking the signature.
A safe reference setup
This setup assumes the Angular app and the API share a site, for example with nginx or the SSR server proxying /api to Node. Same-site requests let you use SameSite=Strict, and the Angular XSRF mechanism works without CORS. The pieces:
- Access token: a JWT, HS256 with a 256-bit secret, valid for 10 minutes, carrying
sub,iss,aud,exp,role,tvandsid(the refresh token family ID). It travels in anHttpOnly,Securecookie. - Refresh token: an opaque random string, not a JWT. Only its SHA-256 hash is stored, with a family ID, an expiry and a used marker. It travels in a cookie with
HttpOnly,Secure,SameSite=Strictand aPathlimited to the auth routes. - CSRF: a JavaScript-readable
XSRF-TOKENcookie bound to the session, checked againstX-XSRF-TOKEN. OWASP's warning applies: always bind the token to session-specific data, because a bare signed token gives little protection.
The __Host- prefix is worth using on the access cookie. MDN's rules for it are that it must be set with Secure by a secure page, with no Domain attribute and Path=/. That last rule is why the refresh cookie, which I scope to the auth routes, cannot carry the prefix.
import jwt from 'jsonwebtoken';
const ISSUER = 'https://api.example.com';
const AUDIENCE = 'example-web';
export function signAccessToken(user: { id: string; role: string; tokenVersion: number }, sid: string) {
return jwt.sign({ role: user.role, tv: user.tokenVersion, sid }, process.env.JWT_SECRET!, {
algorithm: 'HS256',
issuer: ISSUER,
audience: AUDIENCE,
subject: user.id,
expiresIn: 600, // seconds
});
}
export function verifyAccessToken(token: string) {
return jwt.verify(token, process.env.JWT_SECRET!, {
algorithms: ['HS256'], // always an explicit list
issuer: ISSUER,
audience: AUDIENCE,
});
}
On login, set the cookies. maxAge is in milliseconds in Express, and any option you leave out takes the value from RFC 6265:
const base = { httpOnly: true, secure: true, sameSite: 'strict' as const };
res.cookie('__Host-access', accessToken, { ...base, path: '/', maxAge: 10 * 60 * 1000 });
res.cookie('refresh', refreshToken, { ...base, path: '/api/auth', maxAge: 14 * 24 * 60 * 60 * 1000 });
// Readable by Angular on purpose; it is not the credential, only the CSRF token
res.cookie('XSRF-TOKEN', csrfFor(familyId), { secure: true, sameSite: 'strict', path: '/' });
The refresh endpoint is where rotation and reuse detection live. The update is atomic, so two parallel requests cannot both succeed with the same token:
import { createHash, randomBytes } from 'node:crypto';
const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');
export async function rotateRefreshToken(presented: string) {
const record = await RefreshToken.findOneAndUpdate(
{ tokenHash: sha256(presented), usedAt: null },
{ usedAt: new Date() },
); // returns the document as it was before the update
if (!record || record.expiresAt.getTime() < Date.now()) {
const replayed = await RefreshToken.findOne({ tokenHash: sha256(presented) });
if (replayed) await RefreshToken.deleteMany({ familyId: replayed.familyId }); // end the family
throw new UnauthorizedError('Please sign in again');
}
const next = randomBytes(32).toString('base64url');
await RefreshToken.create({
tokenHash: sha256(next), familyId: record.familyId, userId: record.userId,
expiresAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000),
});
return { refreshToken: next, userId: record.userId };
}
The CSRF check compares the header with a value derived from the session, so a token from another session never matches:
import { createHmac, timingSafeEqual } from 'node:crypto';
import type { RequestHandler } from 'express';
export const csrfFor = (sessionId: string) =>
createHmac('sha256', process.env.CSRF_SECRET!).update(sessionId).digest('hex');
export const csrfGuard: RequestHandler = (req, res, next) => {
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next();
const sent = Buffer.from(req.get('x-xsrf-token') ?? '');
const expected = Buffer.from(csrfFor(req.auth.sid)); // req.auth: verified claims, set by your auth middleware
const ok = sent.length === expected.length && timingSafeEqual(sent, expected);
return ok ? next() : res.status(403).json({ message: 'Invalid CSRF token' });
};
On the Angular side, the XSRF header is automatic. The interceptor only has to retry a 401 after one refresh. Make AuthService.refresh() share a single in-flight request, because two tabs or parallel calls that refresh at once would look like a replayed token to the server:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { catchError, switchMap, throwError } from 'rxjs';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const auth = inject(AuthService);
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
const canRetry = error.status === 401 && !req.url.includes('/api/auth/');
if (!canRetry) return throwError(() => error);
// refresh() shares one in-flight request between parallel 401s
return auth.refresh().pipe(switchMap(() => next(req)));
}),
);
};
With server-side rendering, remember that the SSR server makes its own requests. Forward the incoming cookie header to the API for requests made during rendering, and never cache an authenticated response in a shared transfer cache or a CDN.
Checklist before you ship
- Verification passes an explicit
algorithmslist,issuerandaudience. - The secret is generated, at least 256 bits and outside the repository.
- No token is stored in
localStorageorsessionStorage. - Access tokens live for minutes, and there is a revocation path (
tvcounter or a deny list keyed onjti). - Refresh tokens are opaque, hashed at rest, rotated on every use, and replay ends the family.
- Cookies are
HttpOnly,SecureandSameSite, and state-changing requests need the XSRF header. - Login has rate limiting and, for admin users, a second factor.
Short FAQ
Can I use RS256 or EdDSA instead of HS256?
Yes, and you should when other services verify tokens, because they then need only the public key. Keep one algorithm per key and list it in verify. The README says the minimum RSA modulus length is 2048 unless you opt out with allowInsecureKeySizes, which you should not.
Is sessionStorage safer than localStorage?
Only slightly. OWASP's HTML5 cheat sheet says it is scoped to one tab, but both are readable by any script on the page, and OWASP's session management guidance names both as the wrong place for tokens.
Do I need all of this for a small admin panel?
Do the cheap parts always: pinned algorithm, strong secret, claims checked, httpOnly cookie, short expiry. Add refresh rotation when sessions have to outlive the access token.
Sources
All pages were checked on 5 November 2026.
- RFC 8725: JSON Web Token Best Current Practices
- RFC 9700: Best Current Practice for OAuth 2.0 Security (refresh tokens)
- RFC 10017: OAuth 2.0 for Browser-Based Applications
- OWASP: JSON Web Token Cheat Sheet, Session Management, HTML5 Security and CSRF Prevention
- jsonwebtoken README
- MDN: Set-Cookie and Express: res.cookie()
- Angular: security (XSRF protection) and GHSA-jfgx-762w-99vr (CVE-2026-111753)
- Node.js crypto




