Sub topic 16
Why guards are not a security boundary
This chapter assumes you can write a functional canActivate guard, redirect with a UrlTree, and use canMatch with lazy-loaded routes. It also assumes you know basic HTTP status codes and how an Angular app talks to an API. The chapter explains what a guard can and cannot protect, and where real authorization has to happen.
The core problem: the browser belongs to the user
An Angular application is JavaScript that the user's browser downloads and runs. The user controls that environment. They can open DevTools, set breakpoints, overwrite variables, edit localStorage, or run a modified copy of your bundle. A guard is one function inside that bundle, so anyone running the bundle can change what it returns.
Here are some ways a guard gets bypassed. None of them needs special skill.
- Calling the API directly. A user can send
curl https://api.example.com/admin/usersand skip Angular. No router runs, so no guard runs. - Changing client state. If your guard reads
auth.isAdmin()from a flag inlocalStorageor from a decoded token, the user can edit that flag. Decoding a JWT in the browser reads it. It does not verify the signature. - Patching the code. A user can edit the bundle, or use a breakpoint to force
canActivateto returntrue. - Fetching lazy chunks directly. A
canMatchguard stops the router from downloading a lazy chunk for non-admins. The chunk is still a static file at a URL. Anyone who finds the filename can request it and read it.
What guards are actually for
Guards improve the user experience. They keep honest users out of screens that would only show errors. They send logged-out users to the login page, warn about unsaved changes, and avoid downloading code a user will never use. All of that is worth doing. It just cannot stop a determined user.
| Concern | Enforced by | Role of the Angular guard |
|---|---|---|
| Who may read or change data | The server, on every request | None. It can only hide the UI. |
| Who sees which screen | Guard, plus server data checks | Convenience and clear navigation |
| Redirect to login | Guard and an HTTP interceptor | Primary mechanism for UX |
| Unsaved changes warning | `canDeactivate` | Fully the guard's job |
| Keeping admin code private | Not possible in a public bundle | Reduces downloads, hides nothing |
The unsaved-changes guard is a real case where the client is the right place. Nothing about it is a security decision.
Put the decision on the server
Every API endpoint that returns or changes protected data must do two things on its own. It must authenticate the caller by verifying a session or a signed token. It must then authorize the caller by checking that this user may perform this action on this resource.
This Express example shows the shape. The sessions map stands in for your real session store or token verification.
import express, { NextFunction, Request, Response } from 'express';
interface User {
id: string;
roles: string[];
}
// Stand-in for a real session store or signed-token verification.
const sessions = new Map<string, User>([
['token-alice', { id: 'alice', roles: ['admin'] }],
['token-bob', { id: 'bob', roles: ['customer'] }],
]);
function authenticate(req: Request, res: Response, next: NextFunction) {
const token = req.header('Authorization')?.replace('Bearer ', '');
const user = token ? sessions.get(token) : undefined;
if (!user) {
res.status(401).json({ error: 'unauthenticated' });
return;
}
(req as Request & { user?: User }).user = user;
next();
}
function requireRole(role: string) {
return (req: Request, res: Response, next: NextFunction) => {
const user = (req as Request & { user?: User }).user;
if (!user?.roles.includes(role)) {
res.status(403).json({ error: 'forbidden' });
return;
}
next();
};
}
const app = express();
app.get('/admin/users', authenticate, requireRole('admin'), (_req, res) => {
res.json([{ id: 'alice' }, { id: 'bob' }]);
});
app.listen(3000);The status codes matter. 401 means the server does not know who you are. 403 means it knows you and the answer is no. The Angular side should react to both.
Let the client react to server decisions
If the server is the authority, the client must handle its answers. A functional HTTP interceptor turns 401 and 403 responses into navigation, so a session that expires mid-use still ends up at the login page. A guard alone would not catch that, because a guard only runs at navigation time.
import { HttpErrorResponse, HttpInterceptorFn } from '@angular/common/http';
import { inject } from '@angular/core';
import { Router } from '@angular/router';
import { catchError, throwError } from 'rxjs';
export const authErrorInterceptor: HttpInterceptorFn = (req, next) => {
const router = inject(Router);
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) {
router.navigate(['/login'], { queryParams: { returnUrl: router.url } });
} else if (error.status === 403) {
router.navigate(['/forbidden']);
}
return throwError(() => error);
}),
);
};
// In app config:
// provideHttpClient(withInterceptors([authErrorInterceptor]))The interceptor rethrows the error, so the component that made the request can still show its own message.
Common mistakes
- Treating the guard as the only check. The route is "protected", but the API behind it answers anyone. This is the most common and most serious mistake.
- Trusting client-side role data. A flag in
localStorage, or a role claim you decoded yourself, tells the server nothing. The server must read the role from its own session or from a token whose signature it verified. - Returning too much from a resolver. A resolver loads data before the route activates. If it fetches a full record and the component only shows some fields, the extra fields are still visible in the network tab. Make the server return only what this user may see.
- Hiding secrets in lazy chunks. API keys, internal URLs, and "secret" feature logic in an admin bundle are readable by anyone who requests the file. Anything shipped to the browser is public.
- Checking only at navigation time. A user whose permissions are revoked keeps the loaded page open. Only server checks on each request catch this.
Defense in depth, done sensibly
A sound setup layers the checks, and each layer has a distinct job:
- The server authenticates and authorizes every request. This is the security boundary.
- Guards give users accurate navigation and avoid pointless screens and downloads.
- An interceptor handles
401and403consistently, wherever the request came from. - Templates hide buttons the user cannot use, as a courtesy and never as a control.
When you review a feature, test it without Angular. Send the request with curl using a low-privilege token. If the server refuses it, the feature is protected. If it succeeds, the guard was only decoration.
Exercise
Your adminMatchGuard returns false for non-admins, so the admin lazy chunk is never downloaded for them. A teammate says this makes the admin API safe. Give two reasons the claim is wrong and say what actually protects the API.
Show answer
First, the guard runs in the user's browser, so the user can change its result or skip Angular entirely and call the API with curl. Second, the chunk is a static file, so anyone who knows its URL can download it even though the router never requests it. The API is protected only by server-side authentication and authorization on every request, for example a 401 for unknown callers and a 403 for callers without the admin role.