Base64 Encoding with cURL: API Authentication Guide
Learn how to use Base64 encoding with cURL for API authentication. HTTP Basic Auth examples, credential encoding, and Authorization headers.
How to Use Base64 with cURL for API Authentication
Many REST APIs use HTTP Basic Authentication, which requires you to send your credentials encoded in Base64 in the Authorization header. cURL has built-in support for this, but understanding how it works under the hood helps you debug authentication issues and work with APIs that use custom Base64 headers.
The Easy Way: cURL's Built-in -u Flag
# cURL handles Base64 encoding automatically with -u
curl -u username:password https://api.example.com/data
# This is equivalent to manually setting the header:
# Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Manual Base64 Authorization Header
Some APIs need a custom authorization scheme or non-standard Base64 headers. Here is how to encode manually:
# Encode credentials to Base64
echo -n \"username:password\" | base64
# Output: dXNlcm5hbWU6cGFzc3dvcmQ=
# Use the encoded value in the Authorization header
curl -H \"Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=\" \\
https://api.example.com/data
# One-liner: encode and use in a single command
curl -H \"Authorization: Basic $(echo -n 'user:pass' | base64)\" \\
https://api.example.com/data
Encoding API Keys
Some APIs like Stripe and Twilio require the API key as the username with an empty password, or vice versa:
# Stripe: API key as username, empty password
curl -u sk_test_abc123: https://api.stripe.com/v1/charges
# Twilio: Account SID as username, Auth Token as password
curl -u \"ACXXXXX:auth_token\" \\
https://api.twilio.com/2010-04-01/Accounts.json
# SendGrid: \"apikey\" as username, actual key as password
curl -u \"apikey:SG.xxxx\" https://api.sendgrid.com/v3/mail/send
Encoding File Content
# Encode a file to Base64 and send in a JSON payload
BASE64_FILE=$(base64 -w 0 document.pdf)
curl -X POST https://api.example.com/upload \\
-H \"Content-Type: application/json\" \\
-d \"{\\\"file\\\": \\\"$BASE64_FILE\\\", \\\"filename\\\": \\\"document.pdf\\\"}\"
# The -w 0 flag prevents line wrapping in the Base64 output
Troubleshooting Common Issues
- Use
echo -n— without-n, echo adds a newline that gets encoded, corrupting your credentials - Special characters in passwords — wrap credentials in single quotes:
echo -n 'user:p@ss!word' - macOS vs Linux — macOS
base64uses-b 0for no wrapping; Linux uses-w 0 - Verbose mode — use
curl -vto see the actual Authorization header being sent
Security Reminder
Base64 is encoding, not encryption. Anyone who intercepts the Authorization header can decode your credentials instantly. Always use HTTPS when sending Base64-encoded credentials, and prefer token-based authentication (OAuth2, API keys) over Basic Auth when available.