IOLEBA

 IOLEBA N8N Textbook – Table of Contents

Chapter 8: API Authentication Methods
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

  1. Register for API access with the service
  2. Service generates a unique key for you
  3. Include key in every API request
  4. 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:
  1. Add HTTP Request node
  2. Set URL and method
  3. Under Authentication: Select "Header Auth"
  4. Add header: X-API-Key
  5. 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

  1. Combine username and password with colon: user:password
  2. Encode in Base64: dXNlcjpwYXNzd29yZA==
  3. Send in Authorization header: Basic dXNlcjpwYXNzd29yZA==
n8n Configuration:
  1. HTTP Request node
  2. Authentication: "Basic Auth"
  3. Enter username and password
  4. 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

  1. Obtain token (usually by logging in or API request)
  2. Store token securely
  3. Include in Authorization header: Bearer YOUR_TOKEN
  4. 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

  1. Register Application: Get Client ID and Secret from service
  2. Authorization Request: User grants permission
  3. Authorization Code: Service returns temporary code
  4. Token Exchange: Exchange code for access token
  5. Access Resources: Use token to make API requests
  6. 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:
  1. Create OAuth app in service (Google, GitHub, etc.)
  2. Get Client ID and Client Secret
  3. Set redirect URL to n8n's OAuth callback
  4. In n8n credentials, select "OAuth2"
  5. Enter Client ID and Secret
  6. Authorize access (one-time user consent)
  7. 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:
  1. Monitor token expiration time
  2. Refresh before expiration (not after)
  3. Implement retry logic for 401 errors
  4. Store refresh tokens securely
  5. Handle refresh failures gracefully

Real-World Authentication Examples

Example 1: Slack Integration

Authentication Type: OAuth 2.0
  1. Create Slack app at api.slack.com
  2. Get Client ID and Secret
  3. Set OAuth redirect URL
  4. Request scopes: chat:write, channels:read
  5. User authorizes (one-time)
  6. n8n stores and refreshes tokens

Example 2: Stripe Payment API

Authentication Type: API Key (Bearer Token)
  1. Get API key from Stripe dashboard
  2. Use different keys for test/live modes
  3. Include in Authorization header
  4. Format: Bearer sk_test_...

Example 3: Custom Internal API

Authentication Type: JWT
  1. Login endpoint returns JWT
  2. Store JWT in n8n credentials
  3. Include in all subsequent requests
  4. 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:

  1. Create Google Cloud project
  2. Enable Google Sheets API
  3. Create OAuth credentials
  4. Configure in n8n
  5. Authorize access
  6. 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

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