Angular course ยท Module 12: Security and Performance
The three gate guards - authentication
In this lesson3
A samurai fortress has one gate and three guards who together decide who walks through it. An Angular application is built the same way, and this lesson introduces all three roles: the service holds the key (the token), the interceptor stamps every request to the server with it, and the guard lets nobody onto a protected route without that key. We take them one at a time.
One rule carries over from the previous lesson. DomSanitizer.bypassSecurityTrustHtml() is used only for trusted HTML when we deliberately want to bypass sanitization - not always when displaying HTML, not for every input from the user, and it is not deprecated either. Angular sanitizes by default, and you step around that default consciously. The gate works on the same instinct: trust nothing you have not checked.
The first guard: the service holds the key
When you log in, the server issues a token - a digital key that proves who you are. AuthService keeps that key and knows whether you are logged in.
@Injectable({ providedIn: 'root' })
export class AuthService {
private http = inject(HttpClient);
private currentUser = signal<User | null>(null);
readonly isLoggedIn = computed(() => !!this.currentUser());
readonly user = this.currentUser.asReadonly();
login(credentials: LoginCredentials): Observable<AuthResponse> {
return this.http.post<AuthResponse>('/api/auth/login', credentials).pipe(
tap(response => {
localStorage.setItem('access_token', response.accessToken);
this.currentUser.set(response.user);
})
);
}
getToken(): string | null {
return localStorage.getItem('access_token');
}
}Notice two things. The token goes into localStorage so that it survives a page reload - otherwise every F5 would log the user out. And isLoggedIn is a computed derived from the currentUser signal, so the whole application reacts to a login automatically: the user changes, isLoggedIn changes, every view that reads it refreshes. The three lines that build this reactive state must appear in that order - private http = inject(HttpClient); first, then private currentUser = signal<User | null>(null);, and only then readonly isLoggedIn = computed(() => !!this.currentUser());, because a computed can derive only from a signal that already exists. The same service also holds logout(), which clears the stored keys, and refreshToken(), which trades a stored refresh token for a fresh access token - the method the next guard leans on.
The second guard: the interceptor stamps the requests
The server asks for the key on every request. Instead of attaching the token by hand in a hundred places, an interceptor catches each outgoing request and adds the header with the token.
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const authService = inject(AuthService);
const token = authService.getToken();
if (token) {
req = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
}
return next(req);
};The critical part is req.clone - requests in Angular are immutable, so you never add the header to the original; you build a copy of it with Authorization attached. One place in the code, and the token reaches every request in the whole application. That is why an interceptor beats writing the header by hand, and why its type is HttpInterceptorFn - a plain function that uses inject(). Public endpoints can be waved through early with a check on req.context.get(SKIP_AUTH).
The real strength of the interceptor shows when the token expires. Instead of logging the user out, you can quietly refresh the key and repeat the request.
return next(req).pipe(
catchError((error: HttpErrorResponse) => {
if (error.status === 401) { // token expired
return authService.refreshToken().pipe(
switchMap(response => {
const newReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${response.accessToken}`)
});
return next(newReq); // retry with the new key
}),
catchError(() => {
authService.logout(); // the refresh failed too - log out
return throwError(() => error);
})
);
}
return throwError(() => error);
})
);Follow the logic, because this is what authInterceptor does when the server returns status 401: the status means the key is no longer valid, so it tries to refresh the token via refreshToken(), and logs out on failure. switchMap repeats the original request with the new token and the user notices nothing. Only when the refresh fails as well does the inner catchError log the user out. It never reloads the whole page, never retries the request indefinitely, and of course never deletes the user account - it swaps a dead key for a live one. That is the difference between an app that throws you back to the login form every hour and one that simply keeps running.
The third guard: the guard watches the route
The interceptor protects requests, but the route itself - the admin panel, say - is watched by a guard: a function that must return true before Angular lets you onto the page.
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true;
}
return router.createUrlTree(['/login'], { queryParams: { returnUrl: state.url } });
};
export const roleGuard: CanActivateFn = (route) => {
const authService = inject(AuthService);
const requiredRoles = route.data['roles'] as string[];
const user = authService.user();
return !!user && requiredRoles.some(role => user.roles.includes(role));
};The two guards play different parts. authGuard checks whether you are logged in and, if you are not, redirects to the login page while saving returnUrl, so that after logging in you land where you meant to go. roleGuard goes further and asks who you are: do you hold the required role. Both are typed as CanActivateFn - a function using inject() - and that is the modern shape of a guard in Angular 19; there is no @Guard() decorator, no RouteGuardService, and the old CanActivate class implementing an interface now belongs to legacy code. A guard may also answer with a UrlTree instead of a bare false: router.createUrlTree(['/access-denied']) builds one and Angular reads it as "no, go here instead". You plug the guards into a route together.
const routes: Routes = [
{
path: 'admin',
canActivate: [authGuard, roleGuard],
data: { roles: ['admin', 'moderator'] },
loadComponent: () => import('./admin.component')
}
];Angular runs both guards in order and opens /admin only once both return true - first "are you logged in", then "are you an admin or a moderator". Read the route fields from the top: path: 'admin', names it, canActivate: [authGuard, roleGuard], puts the two checks in front of it, data: { roles: ['admin'] }, hands the guard the list of allowed roles, and loadComponent: () => import('./admin.component') pulls in the page only after the guards agree. Because the roles travel in data, the same roleGuard serves any route - you change only the list.
Remember the three guards of this lesson: the service holds the key, the interceptor stamps the requests with it and quietly refreshes it, and the guard watches the entrance to the route. Together they form one gate that nobody slips through.
Code for this lesson: src/app/app.component.ts
import { Component, signal, computed, ChangeDetectionStrategy } from '@angular/core';
import { CommonModule } from '@angular/common';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule],
changeDetection: ChangeDetectionStrategy.OnPush,
template: `
<div class="performance-dojo">
<h1>Angular Performance Optimization</h1>
<section class="strategies">
<h2>Change Detection Strategies</h2>
<div class="strategy-comparison">
<div class="strategy default">
<h3>Default</h3>
<p>Checks the entire component tree on every change</p>
<code>changeDetection: ChangeDetectionStrategy.Default</code>
</div>
<div class="strategy onpush">
<h3>OnPush Recommended</h3>
<p>Checks only when @Input reference, event, or async pipe changes</p>
<code>changeDetection: ChangeDetectionStrategy.OnPush</code>
</div>
</div>
</section>
<section class="demo">
<h2>Demo: List performance</h2>
<div class="controls">
<button (click)="addItems(100)">Add 100 elements</button>
<button (click)="addItems(1000)">Add 1000 elements</button>
<button (click)="clearItems()">Clear</button>
</div>
<div class="stats">
<div class="stat">
<span class="value">{{ items().length }}</span>
<span class="label">Elements</span>
</div>
<div class="stat">
<span class="value">{{ renderCount() }}</span>
<span class="label">Renders</span>
</div>
</div>
<div class="list-container">
@for (item of items(); track item.id) {
<div class="list-item">
{{ item.name }} - {{ item.skill }}
</div>
}
</div>
</section>
<section class="tips">
<h2>Optimization tips</h2>
<div class="tip-grid">
<div class="tip">
<h3>trackBy w @for</h3>
<code>@for (item of items(); track item.id)</code>
<p>Avoid re-rendering the entire list</p>
</div>
<div class="tip">
<h3>OnPush + Signals</h3>
<code>count = signal(0)</code>
<p>Signals automatically notify about changes</p>
</div>
<div class="tip">
<h3>Lazy Loading</h3>
<code>loadComponent: () => import(...)</code>
<p>Load modules on demand</p>
</div>
<div class="tip">
<h3>@defer</h3>
<code>@defer (on viewport) ...</code>
<p>Defer loading of components</p>
</div>
<div class="tip">
<h3>Pure Pipes</h3>
<code>@Pipe({ pure: true })</code>
<p>Cache transformation results</p>
</div>
<div class="tip">
<h3>Virtual Scrolling</h3>
<code><cdk-virtual-scroll-viewport></code>
<p>Render only visible elements</p>
</div>
</div>
</section>
<section class="code-example">
<h2>Optimization examples</h2>
<pre><code>{{ optimizationCode }}</code></pre>
</section>
</div>
`,
styles: [`
.performance-dojo {
font-family: 'Segoe UI', sans-serif;
padding: 20px;
background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
min-height: 100vh;
color: #ecf0f1;
}
h1 {
text-align: center;
color: #f39c12;
}
h2 {
color: #f39c12;
border-bottom: 2px solid #f39c12;
padding-bottom: 10px;
}
section {
background: rgba(255,255,255,0.05);
border-radius: 10px;
padding: 20px;
margin: 20px 0;
}
.strategy-comparison {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
@media (max-width: 600px) {
.strategy-comparison {
grid-template-columns: 1fr;
}
}
.strategy {
padding: 20px;
border-radius: 10px;
}
.strategy.default {
background: rgba(231, 76, 60, 0.2);
border: 2px solid #e74c3c;
}
.strategy.onpush {
background: rgba(46, 204, 113, 0.2);
border: 2px solid #2ecc71;
}
.strategy h3 {
margin-top: 0;
}
.strategy code {
display: block;
background: rgba(0,0,0,0.3);
padding: 10px;
border-radius: 5px;
font-size: 0.85em;
}
.controls {
display: flex;
gap: 10px;
margin-bottom: 20px;
flex-wrap: wrap;
}
button {
padding: 10px 20px;
background: #f39c12;
color: #0f2027;
border: none;
border-radius: 5px;
font-weight: bold;
cursor: pointer;
}
button:hover {
background: #f1c40f;
}
.stats {
display: flex;
gap: 30px;
margin-bottom: 20px;
}
.stat {
text-align: center;
}
.stat .value {
display: block;
font-size: 2em;
font-weight: bold;
color: #f39c12;
}
.stat .label {
color: #888;
}
.list-container {
max-height: 200px;
overflow-y: auto;
background: rgba(0,0,0,0.3);
border-radius: 5px;
padding: 10px;
}
.list-item {
padding: 8px;
margin: 2px 0;
background: rgba(243, 156, 18, 0.1);
border-radius: 3px;
font-size: 0.9em;
}
.tip-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
}
.tip {
background: rgba(0,0,0,0.3);
padding: 15px;
border-radius: 8px;
}
.tip h3 {
margin-top: 0;
color: #f39c12;
font-size: 1em;
}
.tip code {
display: block;
background: rgba(243, 156, 18, 0.2);
padding: 8px;
border-radius: 4px;
font-size: 0.8em;
margin-bottom: 8px;
}
.tip p {
margin: 0;
color: #aaa;
font-size: 0.9em;
}
pre {
background: #0f2027;
padding: 15px;
border-radius: 8px;
overflow-x: auto;
border-left: 4px solid #f39c12;
}
pre code {
color: #ecf0f1;
font-family: 'Fira Code', monospace;
font-size: 0.85em;
}
`]
})
export class AppComponent {
items = signal<SamuraiItem[]>([]);
renderCount = signal(0);
optimizationCode = `// 1. OnPush Change Detection
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
// ...
})
// 2. trackBy w @for
@for (item of items(); track item.id) {
<div>{{ item.name }}</div>
}
// 3. @defer for lazy loading components
@defer (on viewport) {
<app-heavy-component />
} @placeholder {
<div>Loading...</div>
}
// 4. Virtual Scrolling for long lists
<cdk-virtual-scroll-viewport itemSize="50" class="list">
<div *cdkVirtualFor="let item of items">
{{ item.name }}
</div>
</cdk-virtual-scroll-viewport>
// 5. Signals instead of Subject for state
count = signal(0);
doubleCount = computed(() => this.count() * 2);
// 6. A pure pipe for transformations
@Pipe({ name: 'filter', pure: true })
export class FilterPipe implements PipeTransform {
transform(items: any[], predicate: (item: any) => boolean) {
return items.filter(predicate);
}
}`;
addItems(count: number): void {
const newItems: SamuraiItem[] = [];
const startId = this.items().length;
for (let i = 0; i < count; i++) {
newItems.push({
id: startId + i,
name: `Samurai #${startId + i}`,
skill: Math.floor(Math.random() * 100)
});
}
this.items.update(items => [...items, ...newItems]);
this.renderCount.update(c => c + 1);
}
clearItems(): void {
this.items.set([]);
this.renderCount.update(c => c + 1);
}
}
interface SamuraiItem {
id: number;
name: string;
skill: number;
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. When do we use DomSanitizer.bypassSecurityTrustHtml()?
2. What type is a modern functional guard that protects a route in Angular 19?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the guard that checks for the administrator role.
- Vertical ordering
Order the lines that define the reactive logged-in state in AuthService (top to bottom):
- Vertical ordering
Order the fields of the route object protected by a guard (top to bottom):