乐闻世界logo
搜索文章和话题

cURL 如何处理 HTTP 认证(Basic Auth、Bearer Token、OAuth)?

3月7日 19:39

在 cURL 中,认证(Authentication) 是访问受保护资源的关键步骤。cURL 支持多种认证方式,包括 Basic Auth、Bearer Token、OAuth 等。

Basic Authentication

Basic Auth 是最简单的认证方式,将用户名和密码进行 Base64 编码后发送。

bash
# 方式一:使用 -u 参数 curl -u "username:password" https://api.example.com/protected # 方式二:手动编码(不推荐) curl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" \ https://api.example.com/protected # 仅提供用户名,cURL 会提示输入密码 curl -u "username" https://api.example.com/protected # 从环境变量读取密码 curl -u "username:$PASSWORD" https://api.example.com/protected

Bearer Token 认证

Bearer Token 是现代 API 最常用的认证方式。

bash
# 使用 Bearer Token curl -H "Authorization: Bearer your_access_token_here" \ https://api.example.com/protected # 结合其他参数 curl -X POST \ -H "Authorization: Bearer token123" \ -H "Content-Type: application/json" \ -d '{"name":"test"}' \ https://api.example.com/resource # 从文件读取 Token TOKEN=$(cat token.txt) curl -H "Authorization: Bearer $TOKEN" \ https://api.example.com/protected

API Key 认证

API Key 通常通过查询参数或请求头传递。

bash
# 查询参数方式 curl "https://api.example.com/data?api_key=your_api_key_here" # 请求头方式 curl -H "X-API-Key: your_api_key_here" \ https://api.example.com/data # 自定义请求头名称 curl -H "ApiKey: your_api_key_here" \ https://api.example.com/data

OAuth 2.0 认证

OAuth 2.0 是复杂的认证流程,通常包含多个步骤。

bash
# 步骤 1:获取 Access Token curl -X POST https://auth.example.com/oauth/token \ -H "Content-Type: application/x-www-form-urlencoded" \ -d "grant_type=client_credentials" \ -d "client_id=your_client_id" \ -d "client_secret=your_client_secret" # 步骤 2:使用 Access Token 访问资源 curl -H "Authorization: Bearer access_token_from_step1" \ https://api.example.com/protected # OAuth 密码模式 curl -X POST https://auth.example.com/oauth/token \ -d "grant_type=password" \ -d "username=user@example.com" \ -d "password=user_password" \ -d "client_id=your_client_id"

Digest 认证

Digest 认证比 Basic Auth 更安全。

bash
# 使用 --digest 参数 curl --digest -u "username:password" \ https://api.example.com/protected

认证方式对比

认证方式安全性使用场景cURL 参数
Basic Auth低(需 HTTPS)简单场景-u
Bearer TokenAPI 调用-H "Authorization: Bearer"
API Key开放 API-H "X-API-Key" 或查询参数
OAuth 2.0第三方授权多步骤流程
Digest内部系统--digest

实战示例

bash
# GitHub API 认证 curl -H "Authorization: Bearer ghp_xxxx" \ https://api.github.com/user # AWS API(需要签名) curl -X GET "https://s3.amazonaws.com/bucket/file" \ -H "Authorization: AWS4-HMAC-SHA256 ..." # 带认证的完整 API 调用 curl -X POST https://api.example.com/orders \ -H "Authorization: Bearer token123" \ -H "Content-Type: application/json" \ -H "X-Request-ID: $(uuidgen)" \ -d '{"product_id": 123, "quantity": 2}'

安全最佳实践

  1. 使用环境变量:不要在命令行中硬编码密码
  2. HTTPS 必须:认证信息必须通过加密通道传输
  3. Token 过期:定期刷新 Access Token
  4. 权限最小化:只申请必要的权限范围
  5. 日志安全:避免在日志中记录敏感信息
标签:cURL