API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. API Security
  • Introduction
  • Table of Contents
  • API Academy
    • Get Started
      • What is an API?
      • How Does an API Work?
      • How to Call an API?
      • How to Read an API Documentation?
      • Chapter Summary
      • Get realtime weather
    • API Fundamentals
      • API Funtamentals: Overview
      • Method & Path
      • Parameters
      • Request Body
      • Responses
      • API Specification & OAS
      • Chapter Summary
    • Working with APIs
      • Working with APIs: Overview
      • Making Requests from Spec
      • Environments and Variables
      • Chaining Multiple Endpoints
      • Handling Authentication
      • Handling API Signatures
      • Introduction to Scripts
      • Chapter Summary
    • Mocking APIs
      • Mocking APIs: Overview
      • Smart Mock
      • Mock Expectations
      • Cloud Mock
      • Mock Scripts
      • Chapter Summary
    • Designing APIs
      • Designing APIs: Overview
      • Introduction to API Design
      • Creating Your First API Project
      • Analyzing Requirements and Planning Your API
      • Designing Data Models
      • Designing Endpoints
      • Using Components and Reusability
      • Setting Up Authentication
      • API Design Guidelines
      • Chapter Summary
    • Developing APIs
      • Developing APIs: Overview
      • Setup: Install Your AI Coding Assistant
      • Quick Start: From Spec to Running API in 30 Minutes
      • Understanding the Generated Code
      • Testing Your API with Apidog
      • Deployment: Put Your API Online
      • Chapter Summary
    • Testing APIs
      • Testing APIs: Overview
      • Getting Started: Your First Test Scenario
      • Integration Testing and Data Passing
      • Dynamic Values
      • Assertions and Validations
      • Flow Control: If, For, ForEach
      • Data-Driven Testing
      • Performance Testing
      • Test Reports and Analysis
      • CI/CD Integration
      • Scheduled Tasks and Automation
      • Advanced Testing Strategies
      • Chapter Summary
    • API Documentations
      • API Documentations: Overview
      • Publishing Your First API Doc
      • Customizing Documentation Appearance
      • Interactive Features for Consumers
      • Advanced Publishing Settings
      • Managing API Versions
      • Chapter Summary
    • Advanced API Technologies
      • API Technologies: Overview
      • GraphQL
      • gRPC
      • WebSocket
      • Socket.IO
      • Server-Sent Events (SSE)
      • SOAP
      • Chapter Summary
    • API Lifecycle
      • API Lifecycle: Overview
      • Stages of the API Lifecycle
      • API Governance
      • API Security Best Practices
      • Monitoring and Analytics
      • API Versioning Strategies
      • The Future of APIs
      • Chapter Summary
    • API Security
      • API Security: Overview
      • API Security Fundamentals
      • Authentication vs Authorization
      • Understanding OAuth 2.0 and OpenID Connect
      • JSON Web Tokens (JWT)
      • OWASP API Security Top 10
      • Encryption and HTTPS
      • Chapter Summary
    • API Tools
      • API Tools: Overview
      • The Evolution of API Tools
      • API Clients
      • Command Line Tools (cURL, HTTPie)
      • API Design and Documentation Tools
      • API Mocking Tools
      • API Testing Tools
      • All-in-One API Platforms
      • Chapter Summary
    • API Gateway
      • API Gateway: Overview
      • What is an API Gateway?
      • Key Features of API Gateways
      • API Gateway vs Load Balancer vs Service Mesh
      • Popular API Gateway Solutions
      • The BFF (Backend for Frontend) Pattern
      • Chapter Summary
  • Modern Pet Store
    • Pet
      • Get Pet
      • Update Pet
      • Delete Pet
      • Create Pet
      • List Pets
      • Upload Pet Image
    • User
      • Update User
      • Get User
      • Delete User
      • Login
      • Logout
      • Create User
    • Store
      • List Inventory
      • Create Order
      • Get Order
      • Delete Order
      • Callback Example
      • Pay for an Order
    • Payments
      • Pay Order
    • Chat
      • Create Chat Completion
    • Webhooks
      • Pet Adopted Event
      • New Pet Available Event
  • Schemas
    • Pet
    • Category
    • User
    • ApiResponse
    • OrderPayment
    • Tag
    • Order
    • Links-Order
    • PetCollection
    • Bank Card
    • Bank Account
    • Links
    • Error
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. API Security

JSON Web Tokens (JWT)

JSON Web Token (JWT) (pronounced "jot") is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
In the API world, JWTs are the most common format for Access Tokens and ID Tokens.

The Structure of a JWT#

A JWT consists of three parts separated by dots (.):
Header.Payload.Signature
Example: eyJhbGciOiJIUzI1Ni... .eyJzdWIiOiIxMjM0NTY3ODkw... .SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

1. Header#

Describes how the token is signed.
{
  "alg": "HS256",
  "typ": "JWT"
}

2. Payload (Claims)#

Contains the data (claims). There are standard claims and custom claims.
{
  "sub": "1234567890",   // Subject (User ID)
  "name": "John Doe",
  "iat": 1516239022,     // Issued At
  "exp": 1516242622,     // Expiration Time
  "role": "admin"        // Custom claim
}
Note: This data is Base64Url encoded, NOT encrypted. Anyone who has the token can read this data. Do not put secrets here.

3. Signature#

To create the signature part, you have to take the encoded header, the encoded payload, a secret, and the algorithm specified in the header, and sign that.
HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
The signature ensures that the token has not been altered.

How JWT Works in an API#

1.
Authentication: User logs in.
2.
Creation: Server creates a JWT, signing it with a Secret Key (known only to the server).
3.
Response: Server sends the JWT to the Client.
4.
Storage: Client stores it (usually in localStorage or an HttpOnly cookie).
5.
Request: For every subsequent request, the Client sends the JWT in the Authorization header:
Authorization: Bearer <token>
6.
Verification: The Server receives the token. It recalculates the signature using its Secret Key.
If the signatures match -> The token is valid and hasn't been tampered with.
The server uses the data in the Payload (e.g., user_id) to process the request. No database lookup is needed to check the session!

Pros and Cons#

Pros#

Stateless: The server doesn't need to keep a session record in RAM or DB. Good for scalability.
Compact: Small enough to be sent in URLs, POST parameters, or HTTP headers.
Cross-Domain: Works well with CORS and mobile apps.

Cons#

Revocation is Hard: Since the server doesn't track sessions, you can't easily "log out" a user server-side or ban a token before it expires. You often need a "blocklist" (restoring state) or short expiration times to mitigate this.
Size: Can get large if you put too much data in the claims.

Security Best Practices#

1.
Always use HTTPS: Or the token can be stolen in transit.
2.
Short Expiration: Keep exp short (e.g., 15 min) and use Refresh Tokens.
3.
Validate Algorithms: Ensure your server only accepts the algorithms you intend (e.g., prevent "none" algo attacks).

Key Takeaways#

JWTs are self-contained statless tokens used for AuthN and AuthZ.
They are signed (tamper-proof) but encoded (readable by anyone), so never put secrets in the payload.
Always verify the signature before trusting the claims.
Next Step: Now that we know how to secure access, let's look at what attackers do when they find a crack. The OWASP API Security Top 10.
Modified atΒ 2025-12-29 04:30:23
Previous
Understanding OAuth 2.0 and OpenID Connect
Next
OWASP API Security Top 10
Built with