Chapter 8: API Authentication Methods
Introduction
Most modern APIs require authentication to protect data and control access. Understanding authentication methods is essential for integrating n8n with external services. In this chapter, you'll learn the most common authentication patterns, how to implement them in n8n, and best practices for secure API connections.
Why APIs Need Authentication
Authentication Serves Multiple Purposes:
- Security: Prevents unauthorized access to sensitive data
- Rate Limiting: Controls how many requests each user can make
- Tracking: Identifies who is making requests
- Billing: Enables usage-based pricing for paid APIs
- Permissions: Controls what each user can access
Authentication Method Overview
| Method |
Security Level |
Complexity |
Common Use |
| API Key |
Basic |
Simple |
Public APIs, simple services |
| Basic Auth |
Low |
Simple |
Internal tools, legacy systems |
| Bearer Token |
Medium |
Simple |
Modern APIs, SaaS platforms |
| OAuth 2.0 |
High |
Complex |
Google, Facebook, Microsoft |
| JWT |
High |
Medium |
Microservices, modern apps |
API Key Authentication
The simplest authentication method - a unique string that identifies your application.
How API Keys Work
- Register for API access with the service
- Service generates a unique key for you
- Include key in every API request
- Service validates the key
Common API Key Locations
Header (Most Common):
X-API-Key: abc123def456
Authorization: ApiKey abc123def456
Query Parameter:
https://api.example.com/data?api_key=abc123def456
Request Body:
{
"api_key": "abc123def456",
"data": {...}
}
Configuring API Key in n8n
HTTP Request Node Setup:
- Add HTTP Request node
- Set URL and method
- Under Authentication: Select "Header Auth"
- Add header:
X-API-Key
- Value: Your API key
⚠️ API Key Security:
- Never commit API keys to version control
- Store in n8n credentials, not in workflow
- Rotate keys regularly
- Use different keys for development and production
- Revoke compromised keys immediately
Basic Authentication
Uses username and password, encoded in Base64 format.
How Basic Auth Works
- Combine username and password with colon:
user:password
- Encode in Base64:
dXNlcjpwYXNzd29yZA==
- Send in Authorization header:
Basic dXNlcjpwYXNzd29yZA==
n8n Configuration:
- HTTP Request node
- Authentication: "Basic Auth"
- Enter username and password
- n8n handles Base64 encoding automatically
⚠️ Basic Auth Limitations:
- Credentials sent with every request
- Base64 is encoding, NOT encryption
- MUST use HTTPS to protect credentials
- Not recommended for public APIs
- Better for internal/admin tools
Bearer Token Authentication
Modern token-based authentication used by many APIs.
How Bearer Tokens Work
- Obtain token (usually by logging in or API request)
- Store token securely
- Include in Authorization header:
Bearer YOUR_TOKEN
- Token validates your identity
Example Bearer Token Request:
GET /api/user/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Token Lifecycle
Token Management:
- Obtain: Login or API request
- Store: Save in n8n credentials
- Use: Include in API requests
- Refresh: Get new token before expiration
- Revoke: Invalidate when no longer needed
OAuth 2.0 Authentication
The most secure and complex authentication method, used by major platforms.
OAuth 2.0 Flow
- Register Application: Get Client ID and Secret from service
- Authorization Request: User grants permission
- Authorization Code: Service returns temporary code
- Token Exchange: Exchange code for access token
- Access Resources: Use token to make API requests
- Token Refresh: Get new token when expired
OAuth 2.0 Components:
- Client ID: Identifies your application
- Client Secret: Proves application authenticity
- Authorization Code: Temporary code after user approval
- Access Token: Used to make API requests
- Refresh Token: Gets new access token
- Scope: Defines what permissions are requested
n8n OAuth 2.0 Setup
Configuration Steps:
- Create OAuth app in service (Google, GitHub, etc.)
- Get Client ID and Client Secret
- Set redirect URL to n8n's OAuth callback
- In n8n credentials, select "OAuth2"
- Enter Client ID and Secret
- Authorize access (one-time user consent)
- n8n handles token refresh automatically
Popular OAuth 2.0 Services
| Service |
Use Cases |
Scopes Example |
| Google |
Gmail, Drive, Calendar, Sheets |
gmail.readonly, drive.file |
| Microsoft |
Outlook, OneDrive, Teams |
Mail.Read, Files.ReadWrite |
| GitHub |
Repository management, issues |
repo, user, admin:org |
| Slack |
Messages, channels, users |
channels:read, chat:write |
JWT (JSON Web Tokens)
Self-contained tokens that include user information and are cryptographically signed.
JWT Structure
JWT Parts (separated by dots):
header.payload.signature
Example JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VyX2lkIjoxMjMsIm5hbWUiOiJKb2huIn0.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Decoded Payload:
{
"user_id": 123,
"name": "John",
"exp": 1735660800
}
JWT Benefits
- Stateless: Server doesn't need to store sessions
- Self-contained: Token includes all needed info
- Secure: Cryptographically signed
- Portable: Works across different domains
Authentication Best Practices
Credential Management
Security Guidelines:
- Store all credentials in n8n credential manager
- Use descriptive credential names
- Separate dev/staging/production credentials
- Rotate credentials regularly
- Audit credential usage
- Revoke unused credentials
Error Handling
Common Authentication Errors:
| Error Code |
Meaning |
Solution |
| 401 |
Unauthorized |
Check credentials, token might be expired |
| 403 |
Forbidden |
Valid credentials but insufficient permissions |
| 429 |
Too Many Requests |
Rate limit exceeded, implement backoff |
Token Refresh Strategy
Handling Token Expiration:
- Monitor token expiration time
- Refresh before expiration (not after)
- Implement retry logic for 401 errors
- Store refresh tokens securely
- Handle refresh failures gracefully
Real-World Authentication Examples
Example 1: Slack Integration
Authentication Type: OAuth 2.0
- Create Slack app at api.slack.com
- Get Client ID and Secret
- Set OAuth redirect URL
- Request scopes:
chat:write, channels:read
- User authorizes (one-time)
- n8n stores and refreshes tokens
Example 2: Stripe Payment API
Authentication Type: API Key (Bearer Token)
- Get API key from Stripe dashboard
- Use different keys for test/live modes
- Include in Authorization header
- Format:
Bearer sk_test_...
Example 3: Custom Internal API
Authentication Type: JWT
- Login endpoint returns JWT
- Store JWT in n8n credentials
- Include in all subsequent requests
- Monitor expiration, refresh as needed
Practice Exercises
Exercise 1: API Key Integration
Connect to a weather API:
- Sign up for OpenWeatherMap API
- Get free API key
- Create workflow to fetch weather
- Store API key in credentials
- Test with your city
Exercise 2: OAuth 2.0 Setup
Integrate with Google Sheets:
- Create Google Cloud project
- Enable Google Sheets API
- Create OAuth credentials
- Configure in n8n
- Authorize access
- Read data from a spreadsheet
Exercise 3: Multi-Auth Workflow
Build workflow using multiple authentication types:
- Trigger: Webhook (no auth needed)
- Get customer data from database (Basic Auth)
- Lookup details in CRM API (API Key)
- Send email via Gmail (OAuth 2.0)
- Log to Slack (OAuth 2.0)
Key Takeaways
- Different APIs use different authentication methods
- API Keys are simple but less secure
- OAuth 2.0 is most secure for user-authorized access
- JWT tokens are self-contained and stateless
- Always use HTTPS with authentication
- Store credentials in n8n credential manager
- Handle token expiration and refresh proactively
- Implement proper error handling for auth failures
Looking Forward
In Chapter 9, we'll explore webhook workflows in depth. You'll learn to create powerful event-driven automations, handle incoming webhooks from various services, and build real-time integrations that respond instantly to external events.
📥 Download This Chapter
📄 To save as PDF: Press Ctrl+P (Windows) or Cmd+P (Mac)
Your browser's print dialog will open - select "Save as PDF" as the destination
n8n Textbook | Chapter 8: API Authentication Methods
© 2025 IOLEBA | Dr. Marcus Lee
Originally Published: November 2025