API Academy
🌐 English
  • 🌐 English
  • 🌐 繁體中文
HomePetstore APIExplore more APIs
HomePetstore APIExplore more APIs
🌐 English
  • 🌐 English
  • 🌐 繁體中文
🌐 English
  • 🌐 English
  • 🌐 繁體中文
  1. Designing APIs
  • 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. Designing APIs

Setting Up Authentication

Your User module now has well-designed endpoints with schemas and reusable components. But there's a critical piece missing: authentication. Without it, anyone could update or delete any user's data, which is a serious security risk.
In this article, we'll learn how to secure your API using Apidog's Security Schemes, focusing on implementing JWT (JSON Web Token) authentication for the User module. By the end, you'll know how to protect endpoints that require user authentication while keeping public endpoints accessible.

1. Why API Authentication Matters#

Authentication verifies who is making the requestβ€”it ensures that only authorized users can access protected resources.

Without Authentication:#

Anyone can modify or delete user data
No way to track who performed actions
Impossible to implement user-specific features
Security vulnerabilities and data breaches

With Authentication:#

Only authenticated users can access protected endpoints
User actions can be tracked and audited
User-specific data and permissions can be enforced
Your API meets security standards

2. Common Authentication Methods#

Different APIs use different authentication methods. Here are the most common:

1. API Key#

How it works: A unique key is passed in the request (via header, query parameter, or cookie)
Example:
GET /users
X-API-Key: sk_live_abc123xyz456
Use case: Simple authentication for server-to-server communication

2. Bearer Token (JWT)#

How it works: A token (often a JWT) is passed in the Authorization header
Example:
GET /users/usr_123
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Use case: Modern web and mobile apps, stateless authentication
What we'll use for the User module!

3. Basic Authentication#

How it works: Username and password are encoded and sent in the Authorization header
Example:
GET /users
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Use case: Simple authentication, often for admin interfaces

4. OAuth 2.0#

How it works: Industry-standard authorization framework with multiple grant types
Example:
GET /users
Authorization: Bearer <access_token>
Use case: Third-party app integrations, delegated access

3. Understanding Security Schemes in Apidog#

In Apidog, Security Schemes are reusable authentication templates that follow the OpenAPI Specification.

What is a Security Scheme?#

A Security Scheme defines:
The authentication method (API Key, Bearer Token, OAuth 2.0, etc.)
Where credentials are sent (header, query, cookie)
The parameter name (e.g., "Authorization" header)
But it doesn't include actual credentials (like the token value)β€”those are provided separately when testing.

Benefits:#

1.
Define once, use everywhere β€” Create the scheme once, apply to many endpoints
2.
Separation of concerns β€” Template vs. actual credentials
3.
Inheritance β€” Folders and endpoints can inherit security settings
4.
OpenAPI compliant β€” Automatically generates proper OpenAPI security definitions

4. Creating a Security Scheme for the User Module#

For the User module, we'll create a Bearer Token (JWT) security scheme.

Step 1: Navigate to Security Schemes#

1.
In your Apidog project, go to the left sidebar
2.
Navigate to Components β†’ Security Schemes
3.
Click "New Security Scheme"

Step 2: Configure the Security Scheme#

1.
Name: JWT Authentication (or Bearer Token)
2.
Type: Select "Bearer Token"
3.
Format: Enter JWT (this is optional but adds clarity)
Your configuration should look like this:
Security Scheme Name: JWT Authentication
Type: Bearer Token
Bearer Format: JWT
Description: "JWT token-based authentication. Obtain token via POST /user/login"

Step 3: Save the Security Scheme#

Click "Save" to create the security scheme.
Now you have a reusable JWT authentication template!

5. Applying Security Schemes to Endpoints#

There are two ways to apply security schemes: at the folder level (for multiple endpoints) or at the endpoint level (for individual endpoints).

Method 1: Apply at Folder Level (Recommended)#

Applying security at the folder level means all endpoints in that folder automatically inherit the authentication.
Steps:
1.
Select the User Management folder (containing GET, PUT, DELETE /users endpoints)
2.
In the right panel, go to the Auth tab
3.
Select "Security Scheme" as the auth type
4.
Choose "JWT Authentication" from the dropdown
5.
Click "Save"
Now all endpoints in the User Management folder require JWT authentication!

Method 2: Apply at Endpoint Level#

For individual endpoints, you can apply security directly:
1.
Open an endpoint (e.g., PUT /users/{id})
2.
In the Edit tab, scroll to the Request section
3.
Under Authorization, select "Security Scheme"
4.
Choose "JWT Authentication" from the dropdown
5.
Click "Save"
Note: Endpoint-level settings override folder-level settings.

6. Which Endpoints Need Authentication?#

For the User module, let's decide which endpoints need authentication:

Endpoints that REQUIRE authentication:#

GET /users/{id} β€” View user profile (should only see your own or have permission)
PUT /users/{id} β€” Update user data (must be the user or admin)
DELETE /users/{id} β€” Delete user account (must be the user or admin)
POST /user/logout β€” Logout (must be logged in)

Endpoints that DON'T require authentication:#

POST /users β€” Create user (signup is public)
POST /user/login β€” Login (can't be authenticated before logging in!)
But POST /user/login is specialβ€”it doesn't require auth, but it returns a token.

7. Implementing Authentication for the User Module#

Let's apply JWT authentication to the User module endpoints.

Step 1: Apply to Protected Endpoints#

For endpoints that need authentication:
1.
GET /users/{id}:
Open the endpoint
Go to Edit β†’ Request β†’ Authorization
Select "Security Scheme" β†’ "JWT Authentication"
2.
PUT /users/{id}:
Apply the same JWT Authentication security scheme
3.
DELETE /users/{id}:
Apply the same JWT Authentication security scheme
4.
POST /user/logout:
Apply the same JWT Authentication security scheme

Step 2: Leave Login and Signup Public#

For public endpoints:
1.
POST /users (Create user):
Leave Authorization as "No Auth" or "Inherit from parent" if parent is "No Auth"
2.
POST /user/login:
Leave Authorization as "No Auth"
But configure the response to return a token

Step 3: Configure Login Response to Return Token#

The login endpoint should return a JWT token in its response:
1.
Open POST /user/login endpoint
2.
Go to Response tab β†’ 200 Success
3.
Define the response schema:
{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "expiresAt": "2024-12-31T23:59:59Z",
  "user": {
    "id": "usr_3Oy2JIS7TMJgEXfM",
    "email": "jane.smith@example.com",
    "firstName": "Jane",
    "lastName": "Smith"
  }
}
Schema structure:
token (string, required) β€” The JWT token
expiresAt (string, date-time, required) β€” When the token expires
user (object, optional) β€” User information

8. Key Takeaways#

Setting up authentication in Apidog involves:
1.
Security Schemes β€” Reusable authentication templates (JWT, API Key, OAuth 2.0, etc.)
2.
Folder-level vs. Endpoint-level β€” Apply security globally or individually
3.
Public vs. Protected β€” Not all endpoints need authentication
4.
Login Endpoint β€” Public endpoint that returns a token in its response
5.
OpenAPI Compliance β€” Security schemes export properly to OpenAPI format
Benefits:
Security β€” Protect sensitive operations
Consistency β€” Same authentication method across endpoints
Flexibility β€” Override security per endpoint when needed
Clear Documentation β€” Security requirements are clearly documented

What's Next?#

Now that your User module has authentication configured, the next step is to ensure your API follows best practices and design guidelines. In the next article, we'll learn how to use Apidog's API Design Guidelines to maintain consistency and quality across your API design.
Continue with API Design Guidelines.
Modified atΒ 2025-12-25 09:47:55
Previous
Using Components and Reusability
Next
API Design Guidelines
Built with