Coding exercise: implement JWT authentication in an Angular app.
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
- Mention refresh tokens, logout and expiry handling.
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
- Coding exercise: build a Todo application in Angular.
- Coding exercise: create a search box with debounce in Angular.
- Coding exercise: fetch API data and display it in a table in Angular.
- Coding exercise: implement pagination in Angular.
- Coding exercise: create a login form with validation in Angular.
- Coding exercise: build a parent-child communication example in Angular.