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), anAuthService 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
AuthServicewith 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
4. Auth Service
auth.service.ts
5. Login Component
login.component.ts
html
6. Role-Based Authorization in Templates
html
7. Common Mistakes
-
Storing sensitive data in localStorage: JWTs in localStorage are vulnerable to XSS attacks. For high-security apps, consider
httpOnlycookies (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 combinesHttpClient 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 implementCanActivate guards to protect routes and HttpInterceptor to automatically attach JWT tokens to every API request.