Route Guards and HTTP Interceptors
A route guard decides whether a page may open, and sends visitors who aren't signed in to the sign-in page and back again afterwards. An HTTP interceptor sees every request, so one adds the token to every call to your API, and signs the user out when the API answers 401.
Freelancer · Angular · Updated
After this lesson you can
- Protect routes with CanActivateFn guards that send visitors to sign in, and back
- Add the token to API requests with an HttpInterceptorFn, and sign out on a 401
Key takeaways
- A
CanActivateFnguard, put on a route withcanActivate, returnstrueto open the page, or an address fromcreateUrlTreeto send the visitor there instead. signedInGuardsends visitors to/loginwith areturnUrl, so after signing in they land on the page they asked for.- An
HttpInterceptorFn, switched on withprovideHttpClient(withInterceptors([authInterceptor])), adds theAuthorization: Bearerheader to calls to your own/api/only. - On a
401, the interceptor signs the user out and sends them to sign in, andthrowErrorpasses the error on to the component. - A guard is only for the visitor's convenience: the page's code is in the browser, so the data stays safe only because the API checks the token on every request.
The app can sign in. Two jobs are left: keep visitors out of pages they can't use, and send the token with every request to the API. Angular has a tool for each: route guards and HTTP interceptors.
Route guards
A guard is a function the router asks before it opens a page: "may this visitor go here?" It answers true to let them in, or another address to send them to instead. Like a doorman, it checks before you're in the room.
ng generate guard signed-in
If it asks which type, choose CanActivate. Fill in signed-in-guard.ts:
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { Auth } from './auth';
export const signedInGuard: CanActivateFn = (route, state) => {
if (inject(Auth).isSignedIn()) {
return true;
}
return inject(Router).createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};
export const adminGuard: CanActivateFn = () => {
return inject(Auth).isAdmin() ? true : inject(Router).createUrlTree(['/']);
};
- A guard is a plain function, typed
CanActivateFn. It can stillinjectservices. state.urlis the address the visitor wanted, such as/categories/new.createUrlTree(...)makes an address to go to instead. Returning it makes the router go there. Here: the sign-in page, with the wanted address in the query string,/login?returnUrl=%2Fcategories%2Fnew.adminGuardsends signed-in users who aren't admins home.
Put the guards on routes with canActivate:
export const routes: Routes = [
{ path: '', component: Home, title: 'Northwind' },
{ path: 'categories', component: CategoriesPage, title: 'Categories' },
{ path: 'categories/new', component: CategoryForm, title: 'New category', canActivate: [signedInGuard] },
{ path: 'categories/:categoryId', component: CategoryDetails, title: 'Category' },
{ path: 'admin', component: AdminPage, title: 'Admin', canActivate: [adminGuard] },
{ path: 'login', component: Login, title: 'Sign in' },
{ path: 'register', component: Register, title: 'Register' },
{ path: '**', component: NotFound, title: 'Page not found' }
];
categories/new comes before categories/:categoryId: otherwise the parameter route would match first, with new as the id.
Back where they wanted to go
After signing in, the visitor should land on the page they asked for, not the home page. The sign-in page reads returnUrl as a query parameter input, as in Reading Query Parameters. In Login, add the input, and change where next goes:
readonly returnUrl = input<string>();
next: () => this.router.navigateByUrl(this.returnUrl() ?? '/'),
(input comes from @angular/core, and the app needs withComponentInputBinding(), from Reading the Route Parameter.)
Now: a visitor who isn't signed in clicks New category, lands on the sign-in page, signs in, and is taken straight to the new category form.
Like hiding a button, a guard is for the visitor's convenience. The page's code is in the browser, so a determined person can still read it. The data stays safe because the API checks the token on every request.
HTTP interceptors
Every request to the API needs the header Authorization: Bearer <token>. You could add it in every service method, but you'd forget one. An interceptor is a function that sees every request HttpClient sends, on its way out, and every answer on its way back. Like a mailroom that stamps every letter, it's written once.
ng generate interceptor auth
Fill in auth-interceptor.ts:
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
import { Auth } from './auth';
export const authInterceptor: HttpInterceptorFn = (request, next) => {
const auth = inject(Auth);
const router = inject(Router);
const token = auth.token;
if (!token || !request.url.startsWith('/api/')) {
return next(request);
}
const withToken = request.clone({ setHeaders: { Authorization: `Bearer ${token}` } });
return next(withToken).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
auth.logout();
router.navigate(['/login'], { queryParams: { returnUrl: router.url } });
}
return throwError(() => error);
})
);
};
next(request)sends the request on, to the next interceptor or to the server, and returns the observable of its answer.- With no token, or for an address that isn't your API, the request goes on untouched. Never send your token to someone else's server.
- Requests can't be changed, so
clonemakes a copy, andsetHeadersadds the header to it. catchErrorsees failed answers. A 401 means the token has expired or isn't valid any more, so the interceptor signs the user out and sends them to sign in again.throwErrorpasses the error on, so the component's ownerrorhandler still runs.
Interceptors are switched on where HttpClient is set up. This is the reason, from HttpClient in Angular, to add provideHttpClient to app.config.ts, with withInterceptors:
import { ApplicationConfig, provideBrowserGlobalErrorListeners } from '@angular/core';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { authInterceptor } from './auth-interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(withInterceptors([authInterceptor]))
]
};
Nothing else changes. CategoryApi's add, update and delete don't know about tokens, yet every request now carries one.
Try it
With the API and the app running:
- Signed out, open http://localhost:4200/categories/new. You land on the sign-in page, and the address has
?returnUrl=%2Fcategories%2Fnew. - Sign in. You're taken to the new category form. Add a category: it works, because the request carries the token. The browser's developer tools, Network tab, show the
Authorizationheader on the request. - As a user who isn't an admin, open http://localhost:4200/admin: you're sent home.
- Signed in, open Application → Local Storage in the developer tools, and change one character in the middle of the token. Reload the page, so
Authreads the changed token, and add a category. The API answers401, because the signature no longer matches, and the interceptor signs you out and sends you to sign in. (An expired token does the same.)
Do it: decide which requests carry the token
The interceptor adds the token to requests for your API, and to nothing else. Write that decision as a plain JavaScript function that returns the headers to add.
The function gets two values:
url: the request's address ('/api/categories').token: the signed-in user's token ('abc.def.ghi'), ornullwhen nobody is signed in.
For example, authHeaders('/api/categories', 'abc.def.ghi'):
| Question | Answer |
|---|---|
| Is there a token? | Yes: 'abc.def.ghi' |
Does the address start with /api/? |
Yes |
So it returns { Authorization: 'Bearer abc.def.ghi' }.
Your job: write the function authHeaders(url, token), which returns the headers to add, as an object.
- With a token, for an address that starts with
/api/:{ Authorization: ... }, where the value is the wordBearer, a space, and the token. - With no token (
null): an empty object,{}. - For an address that doesn't start with
/api/, such ashttps://maps.example.com/tiles: an empty object,{}, so the token never goes to someone else's server.
Practiced live on the lesson page: write the JavaScript right there and check it.
Check yourself
2 questions to try on the lesson page.
So what
Guards keep visitors out of pages they can't use, and bring them back after signing in; an interceptor adds the token to every API request, and signs out when it stops working. Both make the app pleasant to use. The API's checks are what make it safe.