Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 74 ยท Routing

Authentication with JWT: Tokens, Refresh and Role Guards

Learn how JWT login works in Angular - token anatomy, where to store tokens, a refresh interceptor that avoids request storms, and expiry-aware role guards, with runnable stand-ins.

Most single-page apps talk to an API that needs to know who is calling. A very common design is the JSON Web Token (JWT): the server checks a user's password once, hands back a signed token, and the app sends that token with every later request. This lesson explains what is inside such a token, what the client can and cannot do with it, where to keep it, how to renew it when it expires, and how to wire it into guards.

You have already seen the building blocks: an auth interceptor, functional guards and a complete login flow in the admin dashboard project. Here we add what those lessons only hint at: token anatomy, storage trade-offs, and refreshing an expired token without logging the user out.

Real versus stand-in. The typescript blocks are real Angular code to read and copy; the site cannot compile Angular or call a real login server. The runnable examples re-implement the logic in plain TypeScript with a fake server made of functions: token decoding, an expiry check and the single-flight refresh. The fake token is not signed securely. Real signatures are created and verified only on the server.

What is inside a JWT

A JWT is three Base64URL-encoded parts joined by dots: header.payload.signature. The header names the signing algorithm, the payload holds claims (statements about the user), and the signature lets the server detect tampering.

Common claims have short names: sub (subject, usually the user id), exp (expiry, in seconds since 1970), iat (issued at) and iss (issuer). Apps add their own, such as roles.

Two facts matter for the client:

  1. The payload is encoded, not encrypted. Anyone holding the token can read it. Never put secrets in it.
  2. The client cannot verify the signature, because it does not have the secret key. A token that looks valid in the browser proves nothing. The client may read the claims to improve the interface (show the name, notice that the token expired), but the server must validate every token on every request.

A JWT has three parts

Header Algorithm and type
Payload Claims such as sub, exp, roles
Signature Only the server can check it

Readable by anyone, trustworthy only to the server.

1 / 2

Step 1: a small token reader

Decoding the payload needs only atob after converting Base64URL to ordinary Base64. Keep this logic in one pure function so it is easy to test:

TypeScript
// jwt.ts
export interface Claims {
  sub: string;
  exp: number; // seconds since the epoch
  roles: string[];
}

export function decodeClaims(token: string): Claims | null {
  try {
    const payload = token.split('.')[1];
    const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
    const json = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))
        .join(''),
    );
    return JSON.parse(json) as Claims;
  } catch {
    return null; // not a token we understand
  }
}

export function isExpired(token: string, skewSeconds = 10): boolean {
  const claims = decodeClaims(token);
  if (!claims) return true;
  return claims.exp * 1000 <= Date.now() + skewSeconds * 1000;
}

The skew treats a token as expired a few seconds early. Without it, a token can be valid when you check and expired by the time the request arrives.

Step 2: the auth service

The service stores the session in signals, calls the login and refresh endpoints, and exposes derived values the rest of the app can read.

TypeScript
// auth.service.ts
import { computed, inject, Injectable, signal } from '@angular/core';
import { HttpClient, HttpContext } from '@angular/common/http';
import { firstValueFrom } from 'rxjs';
import { decodeClaims, isExpired } from './jwt';
import { SKIP_AUTH } from './skip-auth';

interface TokenPair {
  accessToken: string;
  refreshToken?: string; // absent when the refresh token lives in an HttpOnly cookie
}

@Injectable({ providedIn: 'root' })
export class AuthService {
  private readonly http = inject(HttpClient);
  private readonly accessToken = signal<string | null>(null);
  private refreshInFlight: Promise<string> | null = null;

  readonly token = this.accessToken.asReadonly();
  readonly claims = computed(() => {
    const t = this.accessToken();
    return t ? decodeClaims(t) : null;
  });
  readonly isSignedIn = computed(() => {
    const t = this.accessToken();
    return t !== null && !isExpired(t, 0);
  });

  async login(email: string, password: string): Promise<void> {
    const pair = await firstValueFrom(
      this.http.post<TokenPair>('/api/login', { email, password }, {
        context: new HttpContext().set(SKIP_AUTH, true),
        withCredentials: true, // lets the server set the refresh cookie
      }),
    );
    this.accessToken.set(pair.accessToken);
  }

  hasRole(role: string): boolean {
    return this.claims()?.roles.includes(role) ?? false;
  }

  /** Several callers share ONE refresh request. */
  refresh(): Promise<string> {
    this.refreshInFlight ??= firstValueFrom(
      this.http.post<TokenPair>('/api/refresh', null, {
        context: new HttpContext().set(SKIP_AUTH, true),
        withCredentials: true,
      }),
    )
      .then(pair => {
        this.accessToken.set(pair.accessToken);
        return pair.accessToken;
      })
      .catch(error => {
        this.logout();
        throw error;
      })
      .finally(() => (this.refreshInFlight = null));
    return this.refreshInFlight;
  }

  logout(): void {
    this.accessToken.set(null);
  }
}

The important line is this.refreshInFlight ??= .... If five requests fail with 401 at the same moment, they must not start five refreshes. Many servers rotate refresh tokens, so a second refresh with the same token would be rejected and could even log the user out. Sharing a single promise solves it.

Where should tokens live?

There is no perfect answer, only trade-offs:

Place Survives reload Readable by injected scripts (XSS) Sent automatically (CSRF risk) Notes
Memory (a signal) No Harder, but a script running in your page can still call your code No Safest for the access token; pair with a refresh cookie
localStorage / sessionStorage Yes / per tab Yes, trivially No Convenient, but one XSS bug leaks the token
HttpOnly + Secure + SameSite cookie Yes No Yes, so you need SameSite and XSRF protection Best for the refresh token

A widely used compromise: keep the short-lived access token (minutes) in memory, and keep the long-lived refresh token in an HttpOnly cookie that the browser sends only to the refresh endpoint. After a page reload the app calls refresh() once at startup to get a new access token. More on cookies and XSS in Security and Accessibility.

Step 3: the refresh interceptor

The interceptor attaches the token, and on a 401 it refreshes once and retries the original request. Requests marked with SKIP_AUTH (login and refresh themselves) are left alone, otherwise a failing refresh would trigger another refresh forever.

TypeScript
// auth.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';
import { SKIP_AUTH } from './skip-auth';

const withToken = (req: HttpRequest<unknown>, token: string) =>
  req.clone({ setHeaders: { Authorization: `Bearer ${token}` } });

export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (req.context.get(SKIP_AUTH) || !req.url.startsWith('/api/')) {
    return next(req);
  }

  const token = auth.token();
  const outgoing = token ? withToken(req, token) : req;

  return next(outgoing).pipe(
    catchError((error: HttpErrorResponse) => {
      if (error.status !== 401) {
        return throwError(() => error);
      }
      return from(auth.refresh()).pipe(
        switchMap(fresh => next(withToken(req, fresh))),
        catchError(refreshError => {
          router.navigate(['/login'], { queryParams: { return: router.url } });
          return throwError(() => refreshError);
        }),
      );
    }),
  );
};

Register it next to the rest of your HTTP setup:

TypeScript
// app.config.ts
provideHttpClient(withFetch(), withInterceptors([authInterceptor]));

The retry is made once: the second next(...) is not wrapped in another refresh. If it fails with 401 again, the user really is not allowed and goes to the login page.

Step 4: run the logic

This stand-in builds a fake unsigned token, decodes it, and runs the same single-flight refresh against a fake server that counts how many refresh calls arrive. Three "requests" fail at the same time; only one refresh should happen.

TypeScript Decoding a token and refreshing once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You should see the old token's claims, then expired now? false (60 seconds is more than the 10-second skew) and true after the clock moves. Three requests succeed after exactly one refresh call. Remove the ??= and make refresh() always call the server to see three refreshes happen.

Step 5: guards that understand tokens

Guards decide whether a route opens. For JWT apps, two rules help: treat an expired token like no token, and give the user a way back (return query parameter). The role logic is the one from Guards, Resolvers and Router Events:

TypeScript
// auth.guards.ts
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';

export const signedInGuard: CanActivateFn = async (_route, state) => {
  const auth = inject(AuthService);
  const router = inject(Router);

  if (auth.isSignedIn()) return true;

  // After a reload the access token is gone, but the refresh cookie may still be valid.
  try {
    await auth.refresh();
    return true;
  } catch {
    return router.createUrlTree(['/login'], { queryParams: { return: state.url } });
  }
};

export const roleGuard =
  (role: string): CanActivateFn =>
  () => {
    const auth = inject(AuthService);
    return auth.hasRole(role) || inject(Router).createUrlTree(['/forbidden']);
  };
TypeScript
// app.routes.ts
{
  path: 'admin',
  canMatch: [signedInGuard, roleGuard('admin')],
  loadComponent: () => import('./admin/admin-page').then(m => m.AdminPage),
},

Using canMatch keeps the admin code from even downloading for users without the role. Remember the warning from the project lesson: this is convenience. A user can change anything in their browser, so the API must check the role again for every request.

Do not log tokens, put them in URLs or query strings, or send them to servers other than your own API. The interceptor above only touches URLs that start with /api/.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Who can verify that a JWT's signature is valid?

    Verifying needs the signing key (or the public key for asymmetric algorithms). The client reads claims for convenience but must not treat them as proof.
  2. 2. Why does AuthService.refresh() reuse an in-flight promise?

    If servers rotate refresh tokens, a second refresh with the same token fails. A shared promise makes concurrent callers wait for the same result.
  3. 3. Why are login and refresh requests marked with SKIP_AUTH?

    Those calls happen before a valid token exists. Sending them through the refresh-on-401 logic could loop forever.
  4. 4. Which storage choice is best for a long-lived refresh token?

    Scripts cannot read an HttpOnly cookie, so an XSS bug cannot copy it. You then need SameSite and XSRF protection for the requests that use it.

Summary

  • A JWT is header.payload.signature; the payload is readable by anyone, and only the server can verify the signature.
  • Read claims on the client for display and expiry planning, never as proof of permission.
  • Keep the access token in memory and the refresh token in an HttpOnly cookie when you can; localStorage tokens are exposed to any XSS bug.
  • A refresh interceptor retries a 401 once, shares one refresh among concurrent requests and skips its own login and refresh calls.
  • Guards treat expired tokens as signed out, try a silent refresh after reload, and use canMatch to keep protected code from downloading.
  • The Angular code is read-only; the token decoding and the refresh logic here are stand-ins.

Next: Forms