Fix n8n Authentication Errors: OAuth, API Keys, and 401 Debugging
Authentication errors are the most common cause of n8n workflow failures. You set up your credentials, test them once, and everything works. Then a week later: “401 Unauthorized.”
This guide covers every type of n8n authentication error, why it happens, and how to fix it fast.
Understanding n8n Authentication Errors
When n8n can’t authenticate with an external service, you’ll see errors like (HTTP 401 and 403 status codes):
NodeApiError: Authentication failed
401 Unauthorized
403 Forbidden - Invalid credentials
The credential is not valid
These errors mean n8n couldn’t prove its identity to the service you’re connecting to. The fix depends on what type of authentication you’re using and what went wrong.
Quick Diagnosis: Which Error Do You Have?
| Error Message | Likely Cause | Jump To |
|---|---|---|
401 Unauthorized | Invalid or expired credentials | API Key Issues |
403 Forbidden | Missing permissions or wrong scopes | OAuth Scope Problems |
invalid_grant | Expired OAuth refresh token | OAuth Token Expiry |
ECONNREFUSED on OAuth | Callback URL misconfigured | OAuth Callback Issues |
The credential is not valid | Credential not saved properly | Credential Storage Issues |
Could not connect | Network or firewall blocking | Network Issues |
API Key Authentication Errors
API key authentication is the simplest—and often the most frustrating when it breaks.
Cause 1: Invalid or Revoked API Key
Symptoms:
401 Unauthorizedon every request- Worked before, suddenly stopped
- Same key works in Postman but not n8n
Why It Happens:
API keys get invalidated for several reasons:
- You regenerated the key in the service’s dashboard
- The service rotated keys automatically
- Someone on your team revoked it
- The account was suspended or downgraded
The Fix:
-
Verify the key is still valid:
Go to the service’s dashboard (Stripe, OpenAI, HubSpot, etc.) and check if the key exists and is active.
-
Generate a new key if needed:
Most services let you create multiple API keys. Generate a fresh one rather than trying to recover the old one.
-
Update the credential in n8n:
Go to Credentials → Find the credential → Edit → Paste the new key → Save (see n8n credentials documentation for detailed steps)
-
Test immediately:
Run a simple workflow to confirm the new key works before assuming you’re done.
Cause 2: Wrong API Key Type
Symptoms:
401or403errors immediately- Key looks correct but doesn’t work
- Error mentions “invalid key format”
Why It Happens:
Many services have multiple key types:
- Publishable vs. Secret keys (Stripe)
- Test vs. Live keys (payment processors)
- Read-only vs. Full access keys
- Project-specific vs. Organization keys (OpenAI)
Using the wrong type causes authentication failures.
The Fix:
Check what key type your n8n node expects:
| Service | Correct Key Type for n8n |
|---|---|
| Stripe | Secret key (starts with sk_) |
| OpenAI | API key (starts with sk-) |
| Twilio | Account SID + Auth Token |
| SendGrid | Full Access API key |
| HubSpot | Private app access token |
Cause 3: API Key Copied Incorrectly
Symptoms:
- Brand new key doesn’t work
- No spaces visible but still fails
- Works when you re-enter it manually
Why It Happens:
Copy-paste introduces invisible characters more often than you’d think:
- Leading/trailing whitespace
- Newline characters from multi-line displays
- Unicode characters that look like spaces
- Quotes accidentally included
The Fix:
// In a Function node, you can verify your key is clean:
const apiKey = $credentials.apiKey;
// Check for hidden characters
console.log('Key length:', apiKey.length);
console.log('Key bytes:', Buffer.from(apiKey).toString('hex'));
// Clean version
const cleanKey = apiKey.trim().replace(/[^\x20-\x7E]/g, '');
console.log('Clean length:', cleanKey.length);
Or simply:
- Delete the entire credential value
- Manually type the first and last few characters
- Copy-paste only the middle portion
- Double-check for quotes or spaces
Cause 4: Environment Mismatch
Symptoms:
- Works in test mode, fails in production (or vice versa)
401errors only on certain workflows- Key valid but returns “resource not found”
Why It Happens:
Test and production environments have separate credentials:
- Stripe test keys don’t access live data
- Sandbox API keys can’t reach production endpoints
- Development tokens have different permissions
The Fix:
-
Identify which environment you need:
- Testing workflows? Use test/sandbox keys
- Production workflows? Use live keys
-
Create separate credentials in n8n:
Stripe (Test)Stripe (Production)
-
Use different credentials per environment:
This prevents accidentally processing test data in production or vice versa.
OAuth Authentication Errors
OAuth errors are trickier because there are more moving parts: tokens, refresh tokens, scopes, and callback URLs.
Cause 1: Expired OAuth Tokens
Symptoms:
invalid_granterror401after credential worked for days/weeks- “Token has been expired or revoked”
Why It Happens:
OAuth uses two types of tokens:
- Access token: Short-lived (1 hour typical), used for API calls
- Refresh token: Long-lived, used to get new access tokens
n8n automatically refreshes access tokens using the OAuth 2.0 refresh token flow, but refresh tokens can expire too:
- Google: Refresh tokens expire after 6 months of inactivity
- Some services expire refresh tokens on password change
- Revoking app access invalidates all tokens
The Fix:
-
Reconnect the credential:
Go to Credentials → Select the OAuth credential → Click Reconnect or Sign in again
-
Complete the OAuth flow:
You’ll be redirected to the service to authorize again
-
Test the connection:
Run a workflow to confirm the new tokens work
Prevention:
For critical workflows, set up monitoring to detect auth failures early. Check out our free workflow debugger to catch these issues before they cascade.
Cause 2: Insufficient OAuth Scopes
Symptoms:
403 Forbiddenon specific operations- Some API calls work, others don’t
- “Insufficient permissions” or “scope” in error
Why It Happens:
OAuth scopes define what your app can do. If you authorized with limited scopes, some operations fail:
// You authorized with:
scope: "read:contacts"
// But you're trying to:
POST /contacts // Requires "write:contacts"
The Fix:
-
Check what scopes your workflow needs:
Look at the n8n node documentation or the API docs for required permissions
-
Reauthorize with correct scopes:
- Delete the existing credential
- Create a new one
- During OAuth, make sure all required scopes are selected
-
For Google specifically:
Google shows a scope selection screen. Expand “See all” and check the permissions your workflows need.
Common Scope Requirements:
| Service | Common Missing Scopes |
|---|---|
| Google Sheets | spreadsheets (not just spreadsheets.readonly) |
| Google Drive | drive or drive.file |
| Gmail | gmail.send for sending emails |
| Slack | chat:write for posting messages |
| HubSpot | Object-specific scopes like crm.objects.contacts.write |
Cause 3: OAuth Callback URL Problems
Symptoms:
- OAuth popup shows error immediately
- “Redirect URI mismatch”
- “Invalid callback URL”
- Works locally, fails on production server
Why It Happens:
OAuth requires the callback URL (where the service sends you after authorization) to match exactly what’s registered in the app settings.
Common mismatches:
httpvshttpslocalhostvs actual domain- Missing or extra trailing slash
- Port number differences
The Fix:
-
Find your n8n callback URL:
In n8n, go to Credentials → Create new → Select the OAuth credential type → Copy the OAuth Redirect URL shown
-
Update the OAuth app settings:
Go to the service’s developer console:
- Google Cloud Console
- Slack API dashboard
- Facebook Developer portal
Add your exact n8n callback URL to the allowed redirect URIs.
-
For self-hosted n8n:
Make sure your
WEBHOOK_URLenvironment variable matches your public URL:WEBHOOK_URL=https://n8n.yourdomain.com -
For local development:
Use ngrok to create a public URL:
ngrok http 5678Then set
WEBHOOK_URLto the ngrok URL and add it to your OAuth app’s allowed redirects.
Cause 4: OAuth App Not Verified
Symptoms:
- “This app isn’t verified” warning
- OAuth flow blocked by service
- Works for your account but not others
Why It Happens:
Google, Microsoft, and other services require apps to be verified before they can be used by anyone other than the developer.
The Fix:
For personal/internal use:
- Add your email to the OAuth app’s test users
- You’ll see a warning but can proceed by clicking “Advanced” → “Go to app”
For production use:
- Submit your app for verification (can take weeks)
- Or use a verified third-party OAuth provider
- For self-hosted n8n, consider using service accounts instead of OAuth
Credential Storage and Encryption Errors
Sometimes the issue isn’t with the external service—it’s how n8n stores or retrieves the credential.
Cause 1: Missing Encryption Key
Symptoms:
- “The credential is not valid”
- Credentials work, then stop after restart
- Multiple credentials fail simultaneously
Why It Happens:
n8n encrypts credentials at rest. If the encryption key changes or is missing, existing credentials become unreadable.
The Fix:
-
Check your encryption key is set:
N8N_ENCRYPTION_KEY=your-32-character-encryption-key -
Ensure it persists across restarts:
- For Docker: Set it in
docker-compose.ymlor.env - For systemd: Set it in the service file
- Never change this key after creating credentials
- For Docker: Set it in
-
If you lost the key:
Unfortunately, you’ll need to recreate all credentials. There’s no way to recover them without the original key.
Cause 2: Credential Not Saved to Database
Symptoms:
- Credential works during setup, fails later
- “Credential not found” errors
- Works in UI but not in executions
Why It Happens:
Database connection issues can prevent credentials from being saved properly:
- SQLite file permissions
- PostgreSQL connection timeout
- Disk space issues
The Fix:
-
Verify database connectivity:
Check your n8n logs for database errors
-
Re-save the credential:
Open the credential, make no changes, and click Save
-
Check database health:
For PostgreSQL:
SELECT * FROM credential_entity WHERE name = 'Your Credential Name';
For more on database issues, see our self-hosting mistakes guide.
Network and Firewall Issues
Authentication can fail before credentials are even checked if n8n can’t reach the service.
Cause 1: Firewall Blocking Outbound Connections
Symptoms:
ECONNREFUSEDorETIMEDOUTerrors- Same credentials work on local machine
- Only affects self-hosted n8n
The Fix:
Ensure your server can reach:
- The API endpoint (e.g.,
api.openai.com) - OAuth endpoints (e.g.,
accounts.google.com) - Usually port 443 (HTTPS)
# Test connectivity
curl -I https://api.openai.com
Cause 2: Proxy Configuration
Symptoms:
- Works locally, fails on corporate network
ECONNRESETerrors- Partial connectivity (some services work)
The Fix:
Configure n8n to use your proxy:
HTTP_PROXY=http://proxy.yourcompany.com:8080
HTTPS_PROXY=http://proxy.yourcompany.com:8080
Service-Specific Authentication Fixes
Google Services (Sheets, Gmail, Drive)
Common Issues:
-
“Access blocked: Authorization Error”
- Your OAuth app needs to be in testing mode with your email added as a test user
- Or submit for verification
-
“Token has been expired or revoked”
- Reconnect the credential (Google expires tokens after 6 months of inactivity)
-
“Request had insufficient authentication scopes”
- Delete and recreate credential with all required scopes selected
OpenAI
Common Issues:
-
“Incorrect API key provided”
- Verify you’re using an API key from your OpenAI dashboard, not an organization ID
- Check the key starts with
sk-
-
“You exceeded your current quota”
- This isn’t an auth error—it’s billing. Add credits to your OpenAI account
-
“Organization not found”
- You may need to specify the organization ID in the credential settings
Slack
Common Issues:
-
“not_authed” or “invalid_auth”
- Token expired or was revoked
- Reinstall the Slack app to your workspace
-
“missing_scope”
- Your Slack app doesn’t have the required permissions
- Go to api.slack.com, add the scope, reinstall the app
HubSpot
Common Issues:
-
“INVALID_AUTHENTICATION”
- For Private Apps: Check the access token is correct
- For OAuth: Reconnect the credential
-
“MISSING_SCOPES”
- Edit your Private App or OAuth app to include required scopes
- Regenerate the access token after adding scopes
Debugging Authentication Step by Step
When you can’t identify the cause, use this systematic approach:
Step 1: Verify Credentials Outside n8n
Test your credentials work independently:
# For API keys
curl -H "Authorization: Bearer YOUR_API_KEY" https://api.service.com/test
# For Basic Auth
curl -u username:password https://api.service.com/test
If this fails, the issue is with the credential itself, not n8n.
Step 2: Check n8n Logs
For self-hosted n8n:
# Docker
docker logs n8n
# Systemd
journalctl -u n8n -f
Look for:
- Specific error codes (401, 403)
- Token-related errors
- Connection errors
Step 3: Enable Debug Mode
Add to your environment:
N8N_LOG_LEVEL=debug
This provides detailed information about credential usage and API requests.
Step 4: Test with HTTP Request Node
Create a simple workflow with the HTTP Request node:
- Add HTTP Request node
- Set the URL to a simple endpoint (like
/meor/user) - Configure authentication manually
- Check the response
This isolates whether the issue is with the credential or the specific node.
Step 5: Compare Working vs. Failing Requests
If some workflows work and others don’t:
- Check what’s different (endpoint, method, parameters)
- Look for permission-related patterns
- Verify rate limits aren’t being hit
Preventing Authentication Errors
Use Credential Testing
Before deploying workflows:
- Edit the credential
- Click “Test Connection” if available
- Run a simple test workflow
Monitor Credential Health
Set up an error handling workflow:
Error Trigger → IF (auth error) → Send Alert
This catches authentication failures immediately rather than discovering them days later.
Document Your Credentials
Keep track of:
- When credentials were created
- What scopes/permissions they have
- When tokens expire
- Who has access to regenerate them
Rotate Credentials Proactively
Don’t wait for credentials to break:
- Set calendar reminders for OAuth re-authentication (every 3-5 months for Google)
- Rotate API keys quarterly for sensitive services
- Document the rotation process so anyone on your team can do it
Quick Reference: Authentication Error Codes
| Code | Meaning | Action |
|---|---|---|
| 401 | Invalid credentials | Check API key/token is correct and active |
| 403 | Valid credentials, wrong permissions | Add required scopes or permissions |
400 invalid_grant | OAuth token expired | Reconnect the OAuth credential |
400 invalid_client | OAuth app misconfigured | Check client ID/secret match |
| 429 | Rate limited (not auth) | Wait and retry, reduce request frequency |
Need Help?
Authentication issues can be time-consuming to debug. If you’re stuck:
- Try our workflow debugger for automated error analysis
- Use our workflow auditor to check credential configuration
- For persistent issues, our support retainer provides direct expert help
The right credential configuration prevents hours of debugging. Get it right once, document it, and monitor for failures—your future self will thank you.
Frequently Asked Questions
Why does my n8n credential work sometimes and fail other times?
Intermittent authentication failures usually indicate token expiration or rate limiting. OAuth access tokens expire (typically after 1 hour), and n8n refreshes them automatically—but if the refresh token expires or is revoked, authentication fails. Check if failures correlate with time patterns. For API keys, intermittent failures often mean you’re hitting rate limits, which return 429 errors that can look like auth failures.
How do I fix “401 Unauthorized” in n8n?
A 401 error means your credentials are invalid or expired. First, verify the credential still works by testing it outside n8n (using curl or Postman). If it works externally, re-enter the credential in n8n—copy-paste can introduce hidden characters. For OAuth credentials, click “Reconnect” to get fresh tokens. For API keys, confirm you’re using the correct key type (secret vs. publishable, test vs. live).
Why does my Google OAuth credential stop working after a few months?
Google expires OAuth refresh tokens after 6 months of inactivity. If your workflow doesn’t run for 6 months, the token becomes invalid and you’ll need to reconnect. Additionally, if your Google OAuth app is in “testing” mode, refresh tokens expire after 7 days. To prevent this, either submit your app for verification or ensure workflows run regularly to keep tokens active.
How do I debug n8n authentication errors on self-hosted instances?
Set N8N_LOG_LEVEL=debug in your environment variables and check the logs (docker logs n8n or journalctl -u n8n). Verify your WEBHOOK_URL is correctly set to your public URL—OAuth callbacks will fail if this is misconfigured. Also confirm your N8N_ENCRYPTION_KEY hasn’t changed, as this would make all existing credentials unreadable. Test outbound connectivity to ensure your server can reach external APIs.
Can I use the same API key in multiple n8n credentials?
Yes, you can use the same API key in multiple credentials, but it’s not always recommended. Having the same key in multiple places makes rotation harder and increases the blast radius if the key is compromised. Better practice: create one credential per service and reference it across workflows. If you need environment separation (test vs. production), create separate credentials with clearly named labels like “Stripe (Production)” and “Stripe (Test)”.