Skip to main content
Angular Basics
CHAPTER 21 Beginner

Authentication and Authorization

Updated: May 18, 2026
5 min read

# CHAPTER 21

Authentication and Authorization

1. Chapter Introduction

Authentication (who are you?) and Authorization (what can you do?) are critical for any production application. In Angular, we implement these using JWT (JSON Web Tokens), an AuthService to manage the auth state, and Route Guards to protect private pages. This chapter builds a complete, production-ready authentication system.

2. Learning Objectives

  • Understand JWT-based authentication flow.
  • Build an AuthService with login, logout, and token management.
  • Protect sensitive routes using Route Guards.
  • Implement role-based access control.
  • Build a Login Application.

3. JWT Authentication Flow

text
1234567
1. User submits login form (email + password)
2. Angular sends POST /api/login to backend
3. Backend validates credentials, returns { token: "eyJ..." }
4. Angular stores the JWT in localStorage
5. All subsequent API requests include the token in the Authorization header
6. Backend validates the token on protected endpoints
7. On logout, Angular removes the token from localStorage

4. Auth Service

auth.service.ts
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable, tap } from 'rxjs';
import { Router } from '@angular/router';

export interface LoginResponse {
  token: string;
  user: { id: number; name: string; role: string };
}

@Injectable({ providedIn: 'root' })
export class AuthService {
  private apiUrl = 'https://api.example.com/auth';
  private isLoggedIn$ = new BehaviorSubject<boolean>(this.hasToken());

  constructor(private http: HttpClient, private router: Router) {}

  private hasToken(): boolean {
    return !!localStorage.getItem(&#039;auth_token&#039;);
  }

  login(email: string, password: string): Observable<LoginResponse> {
    return this.http.post<LoginResponse>(`${this.apiUrl}/login`, { email, password })
      .pipe(
        tap(response => {
          localStorage.setItem(&#039;auth_token&#039;, response.token);
          localStorage.setItem(&#039;user&#039;, JSON.stringify(response.user));
          this.isLoggedIn$.next(true);
        })
      );
  }

  logout(): void {
    localStorage.removeItem(&#039;auth_token&#039;);
    localStorage.removeItem(&#039;user&#039;);
    this.isLoggedIn$.next(false);
    this.router.navigate([&#039;/login&#039;]);
  }

  getToken(): string | null {
    return localStorage.getItem(&#039;auth_token&#039;);
  }

  getCurrentUser(): any {
    const user = localStorage.getItem(&#039;user&#039;);
    return user ? JSON.parse(user) : null;
  }

  isAuthenticated(): Observable<boolean> {
    return this.isLoggedIn$.asObservable();
  }

  hasRole(role: string): boolean {
    const user = this.getCurrentUser();
    return user?.role === role;
  }
}

5. Login Component

login.component.ts
1234567891011121314151617181920
@Component({ selector: &#039;app-login&#039;, templateUrl: &#039;./login.component.html&#039; })
export class LoginComponent {
  email = &#039;&#039;;
  password = &#039;&#039;;
  error = &#039;&#039;;
  loading = false;

  constructor(private authService: AuthService, private router: Router) {}

  onLogin(): void {
    this.loading = true;
    this.authService.login(this.email, this.password).subscribe({
      next: () => this.router.navigate([&#039;/dashboard&#039;]),
      error: () => {
        this.error = &#039;Invalid email or password.&#039;;
        this.loading = false;
      }
    });
  }
}
html
12345678
<form (ngSubmit)="onLogin()">
  <input [(ngModel)]="email" name="email" type="email" placeholder="Email" />
  <input [(ngModel)]="password" name="password" type="password" placeholder="Password" />
  <div *ngIf="error" class="error">{{ error }}</div>
  <button type="submit" [disabled]="loading">
    {{ loading ? &#039;Logging in...' : 'Login' }}
  </button>
</form>

6. Role-Based Authorization in Templates

html
123456789101112
<!-- Show admin panel only if user is an admin -->
<div *ngIf="authService.hasRole(&#039;admin')">
  <a routerLink="/admin">Admin Panel</a>
</div>

<!-- Show user-specific content -->
<ng-container *ngIf="authService.getCurrentUser() as user">
  <p>Welcome, {{ user.name }}!</p>
</ng-container>

<!-- Logout button -->
<button (click)="authService.logout()">Logout</button>

7. Common Mistakes

  • Storing sensitive data in localStorage: JWTs in localStorage are vulnerable to XSS attacks. For high-security apps, consider httpOnly cookies (managed by backend). For most apps, localStorage is acceptable with proper XSS mitigation.
  • Only protecting routes on the frontend: Frontend route guards are UX features, not security. The backend API must always validate the JWT token independently.

8. MCQs with Answers

Question 1

What is JWT?

Question 2

Where is the JWT typically stored in an Angular app?

Question 3

How is the JWT sent to the backend for protected API requests?

Question 4

What RxJS operator is used in the AuthService to perform a side effect (storing token) without changing the stream?

Question 5

Why should backend APIs validate the JWT independently, not rely on Angular guards?

Question 6

What BehaviorSubject is used for in the AuthService?

Question 7

What method clears the token and redirects to login?

Question 8

What method checks if a user has a specific role for role-based authorization?

Question 9

What is "role-based access control" (RBAC)?

Question 10

What is the security risk of storing JWTs in localStorage?

9. Interview Questions

  • Q: Walk me through the complete JWT authentication flow from login to a protected API request.
  • Q: What is the difference between Authentication and Authorization?

10. Summary

Authentication in Angular combines HttpClient for token retrieval, localStorage for storage, BehaviorSubject for reactive auth state, and Route Guards for protecting views. This pattern is battle-tested across thousands of production Angular applications.

11. Next Chapter Recommendation

We referenced Route Guards in this chapter. In Chapter 22: Angular Guards and Interceptors, we implement CanActivate guards to protect routes and HttpInterceptor to automatically attach JWT tokens to every API request.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·