Coding exercise: implement JWT authentication in an Angular app.

Angular practical coding · Freshers and experienced

Model answer

The login call returns a signed token. An HTTP interceptor adds it to each request, and a route guard blocks pages when there is no token. An httpOnly cookie set by the server is safer than localStorage because scripts cannot read it. Know that trade-off.

// auth.interceptor.ts
export const authInterceptor: HttpInterceptorFn = (req, next) => {
  const token = localStorage.getItem('token');
  const authed = token ? req.clone({ setHeaders: { Authorization: 'Bearer ' + token } }) : req;
  return next(authed).pipe(
    catchError((err) => {
      if (err.status === 401) { localStorage.removeItem('token'); inject(Router).navigateByUrl('/login'); }
      return throwError(() => err);
    }),
  );
};

// auth.guard.ts
export const authGuard: CanActivateFn = () =>
  localStorage.getItem('token') ? true : inject(Router).parseUrl('/login');

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

// routes
export const routes: Routes = [
  { path: 'account', canActivate: [authGuard], loadComponent: () => import('./account').then((m) => m.Account) },
];

On the server, hash passwords with bcrypt, sign with a secret from the environment and a short expiry, and verify the token in middleware. A guard only hides pages; the API must enforce access.

Tips

Practise it yourself in the React and Angular code playground.

Learn this topic

Angular Tutorial: Beginner to Advanced .

Sign in to add your own answer.

More questions