Objectives
By the end of this module, you will be able to:- Understand authentication and authorization concepts.
- Compare different authentication mechanisms.
- Understand how JWT-based authentication works.
- Implement secure user authentication using JWT.
- Protect REST APIs using JWT.
- Implement role-based authorization.
Topics Covered
In this module, you’ll learn:- Authentication & Authorization Fundamentals
- JWT Authentication Fundamentals
- Preparing for JWT Implementation
- Authentication Building Blocks
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download
1. Authentication & Authorization Fundamentals
Introduction
Most web applications and REST APIs expose resources that should only be accessible to authenticated users. Before allowing access, an application must verify the user’s identity and determine what resources they are allowed to access. This section introduces the fundamental concepts of authentication and authorization and explains the different mechanisms used to secure modern web applications and APIs.Topics
- Why APIs Need Security
- Authentication
- Authorization
- Authentication vs Authorization
- Basic Authentication
- Session-Based Authentication
- Token-Based Authentication (JWT)
- Comparison of Authentication Mechanisms
- When to Use JWT
1. Basic Authentication
Key Points
- Simplest authentication mechanism.
- Client sends username and password with every request.
- Credentials are sent in the
Authorizationheader. - Server validates the credentials for every request.
- Stateless authentication.
- Should always be used over HTTPS.
Flow
2. Session-Based Authentication
Key Points
- User logs in once using username and password.
- Server validates the credentials.
- Server creates a session.
- Session ID is returned to the client.
- Client sends the Session ID with every subsequent request.
- Server maintains session information.
- Stateful authentication.
- Commonly used in traditional web applications.
Flow
3. Token-Based Authentication (JWT)
Key Points
- User logs in once using username and password.
- Server validates the credentials.
- Server generates a signed JWT.
- JWT is returned to the client.
- Client stores the token.
- Client sends the JWT with every subsequent request.
- Server validates the JWT before processing the request.
- Stateless authentication.
- Widely used in REST APIs, mobile applications, and microservices.
Flow
Comparison
When to Use JWT
Use JWT when:- Building REST APIs.
- Developing mobile applications.
- Building microservices.
- Creating stateless applications.
- Supporting multiple clients (Web, Mobile, Third-Party APIs).
Authentication
Authentication is the process of verifying the identity of a user, application, or system before granting access to protected resources. It answers the question:“Who are you?”During authentication, the application validates the credentials provided by the user, such as a username and password, OTP, biometric data, or security token. If the credentials are valid, the user is considered authenticated and can proceed to access the application.
Examples
- Logging in with an email and password.
- Signing in using Google or GitHub.
- Verifying a user with a One-Time Password (OTP).
- Fingerprint or Face ID authentication.
Authorization
Authorization is the process of determining what an authenticated user is allowed to access or perform within an application. It answers the question:“What are you allowed to do?”After authentication is successful, the application checks the user’s permissions or roles to determine which resources and operations they are authorized to access.
Examples
- An Admin can create, update, and delete students.
- A Teacher can view and update student records.
- A Student can only view their own profile.
- An authenticated user cannot access resources without sufficient permissions.
Authentication vs Authorization
Why Secure APIs?
- Protect sensitive user and business data.
- Prevent unauthorized access.
- Ensure only authenticated users can access resources.
- Restrict operations based on user roles and permissions.
- Prevent malicious activities and data manipulation.
2. JWT Authentication Fundamentals
Objective
Understand what JWT is, why it is preferred for modern REST APIs, and how JWT-based authentication works.Introduction
JSON Web Token (JWT) is an open standard (RFC 7519) for securely transmitting information between a client and a server as a digitally signed JSON object. Instead of sending user credentials with every request or maintaining server-side sessions, the client sends a signed JWT to access protected resources.Topics
- What is JWT?
- Why JWT?
- JWT Architecture
- Components of JWT
- JWT Claims
- JWT Authentication Flow
- Access Token & Token Expiration
What is JWT?
JWT (JSON Web Token) is a compact, URL-safe token that contains user information (claims) and is digitally signed by the server. After successful login, the server generates a JWT and sends it to the client. The client includes this token in subsequent requests to access protected APIs.JWT Architecture
Components of JWT
A JWT consists of three parts separated by dots (.).
Header
Contains metadata about the token.Payload
Contains user information called claims.Signature
Used to verify the integrity of the token. It is generated using:- Header
- Payload
- Secret Key
- Signing Algorithm
JWT Claims
Claims are pieces of information stored inside the payload.Registered Claims
sub– Subjectiss– Issueraud– Audienceiat– Issued Atexp– Expiration Time
Public Claims
Shared custom claims. Example:- username
Private Claims
Application-specific claims. Example:- role
- permissions
Access Token
An Access Token is the JWT returned after successful authentication. The client sends it with every protected request.Token Expiration
JWTs have a limited lifetime defined by theexp claim.
When the token expires, the user must authenticate again or obtain a new token.
JWT Authentication Flow
Why JWT?
JWT is widely used because it:- Eliminates server-side session management.
- Supports stateless authentication.
- Scales well across distributed systems.
- Is ideal for REST APIs, mobile applications, and microservices.
Comparison of Authentication Mechanisms
3. Preparing for JWT Implementation
Objective
Understand the libraries, FastAPI components, and implementation flow required to build JWT-based authentication in a FastAPI application.Required Libraries
Install the following libraries:Purpose of Each Library
FastAPI Components
OAuth2PasswordBearer vs HTTPBearer
FastAPI provides two main security schemes infastapi.security for implementing token-based authentication: OAuth2PasswordBearer and HTTPBearer. Understanding their differences helps select the right scheme for your security requirements.
1. OAuth2PasswordBearer
- Flow: Implements the OAuth2 password flow. It requires a
tokenUrlparameter that specifies the path to the login endpoint (e.g./auth/login). - Swagger Integration: Swagger UI displays an Authorize button. When clicked, it provides form fields for Username and Password. It sends a POST request with form-data to the
tokenUrl, retrieves the token, and automatically applies it to subsequent test requests. - Header Parsing: Directly extracts the token value as a
strfrom theAuthorizationheader. - Default Error: Automatically raises a
401 Unauthorizedexception if the token is missing.
2. HTTPBearer
- Flow: A generic HTTP security scheme for Bearer token authentication (RFC 6750) that is independent of any specific OAuth2 login flow. It does not require a
tokenUrl. - Swagger Integration: Swagger UI displays an Authorize button. When clicked, it asks directly for the Token value.
- Header Parsing: Returns an instance of
HTTPAuthorizationCredentials, which wraps the parsing details (e.g.,credentials.schemewhich is"Bearer", andcredentials.credentialswhich is the actual token string). - Default Error: Automatically raises a
403 Forbiddenexception if the token is missing.
Comparison Table
JWT Authentication Flow
Authentication Building Blocks
Objective
Implement the core building blocks of JWT authentication using simple Python programs before integrating them into a FastAPI application.Step 1: Install the Required Libraries
Objective
Install the libraries required for password hashing and JWT token generation.Instructions
Install the following libraries:Step 2: Hash a Password
Objective
Securely hash a password before storing it in the database.Instructions
- Import
PasswordHash. - Create a password hasher.
- Hash the password.
- Display the hashed password.
Verify
- Run the program.
- Observe that the output is a hashed password instead of the original password.
Step 3: Verify a Password
Objective
Verify whether the entered password matches the stored hashed password.Instructions
- Hash a password.
- Verify the entered password against the stored hash.
- Display the verification result.
Verify
Expected OutputStep 4: Generate a JWT
Objective
Generate a signed JWT containing user information.Instructions
- Define the Secret Key.
- Define the Signing Algorithm.
- Create the JWT payload.
- Set the token expiration time.
- Generate the JWT.
- Display the generated token.
Verify
- Run the program.
- Observe that a JWT token is generated.
Step 5: Validate a JWT
Objective
Validate a JWT and extract the user information stored inside it.Instructions
- Decode the JWT.
- Verify the signature.
- Verify the expiration time.
- Display the decoded payload.
Verify
Expected OutputStep 6: Read the JWT Claims
Objective
Retrieve the information stored inside the JWT payload.Instructions
- Read the user ID.
- Read the username.
- Read the user role.
- Display the values.
Verify
Expected OutputObjective
Create a simple Python program to verify that all the authentication building blocks work correctly. The program should:- Hash a password.
- Verify the password.
- Generate a JWT.
- Validate the JWT.
- Read the user information stored inside the JWT.
Solution
Solution
Verify
Verify that the program:- Hashes the password successfully.
- Verifies the correct password.
- Rejects an incorrect password.
- Generates a JWT token.
- Successfully validates the generated token.
- Extracts the user information from the JWT.
Expected Output ?
Show Output
Show Output
Note: In the next section, we will integrate these helper functions into a FastAPI application to implement user registration, login, and protected REST APIs.
Practice
To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:Follow-Along Practice
Practice secure password hashing with pwdlib, signing and validating JSON Web Tokens with python-jose, and securing endpoints.💻 VS Code | 🚀 Colab | 📥 Download
Summary
- The distinction between authentication (who you are) and authorization (what you can do).
- Different authentication models (Basic, Session-based, and Token-based).
- The structure of JSON Web Tokens (Header, Payload, Signature).
- How to securely hash passwords and sign/decode tokens.