curl Authentication (Basic and Bearer Token)
Master curl authentication with Basic Auth (-u flag) and Bearer tokens. Learn OAuth2 flows, .netrc files, token security, and credential best practices.
Detailed Explanation
Authentication with curl
curl supports multiple authentication methods. The two most common are HTTP Basic Authentication and Bearer Token authentication, each suited to different scenarios.
Basic Authentication with -u
curl provides the -u flag for Basic Auth:
curl -u username:password https://api.example.com/protected
curl automatically Base64-encodes the credentials and sends them in the Authorization header as Basic dXNlcm5hbWU6cGFzc3dvcmQ=. Omit the password to have curl prompt you interactively, keeping it out of shell history:
curl -u username https://api.example.com/protected
You can also set the header manually:
curl -H "Authorization: Basic $(echo -n 'username:password' | base64)" \
https://api.example.com/protected
Using .netrc for Stored Credentials
For repeated authentication, store credentials in a ~/.netrc file:
machine api.example.com
login username
password secretpass
Then use --netrc:
curl --netrc https://api.example.com/protected
Bearer Token Authentication
Bearer tokens are the standard for modern APIs using OAuth 2.0 or JWTs:
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." \
https://api.example.com/me
OAuth 2.0 Token Flow
A typical flow involves obtaining a token first, then using it:
TOKEN=$(curl -s -X POST https://auth.example.com/oauth/token \
-d "grant_type=client_credentials" \
-d "client_id=$CLIENT_ID" \
-d "client_secret=$CLIENT_SECRET" | jq -r '.access_token')
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/resources
Security Best Practices
- Never hardcode credentials in version-controlled scripts
- Use environment variables:
curl -u "$API_USER:$API_PASS"or-H "Authorization: Bearer $TOKEN" - Always use HTTPS to prevent credential interception
- Rotate tokens regularly and revoke compromised ones
- Prefer Bearer tokens over Basic Auth when possible, as they can be scoped and expired without changing passwords
Use Case
A developer needs to authenticate API requests using either Basic Auth credentials for internal services or Bearer tokens for OAuth 2.0 protected endpoints.