正在加载,请稍候…

如何在 curl、Postman、fetch 和 Python 中发送 Basic Auth

提供 curl、Postman、JavaScript fetch、Python requests 和 Node.js 发送 HTTP Basic Authent

如何在 curl、Postman、fetch 和 Python 中发送 Basic Auth

每个示例都做的一件事

Basic Auth 始终归结为一个请求头:Authorization: Basic base64(username:password)。下面的每个工具要么为你构建该请求头,要么让你直接设置它。如果你只需要编码后的值,请将你的凭据粘贴到 Basic Auth 生成器 中并复制该请求头。

如何在 curl、Postman、fetch 和 Python 中发送 Basic Auth 插图

curl

-u 标志是快捷方式——curl 会为你编码凭据:

curl -u admin:secret123 https://api.example.com/data

或者显式设置请求头(在脚本编写时很有用):

curl -H "Authorization: Basic $(printf '%s' 'admin:secret123' | base64)" \
  https://api.example.com/data

使用 printf(而不是 echo),这样就不会有尾随换行符破坏令牌。

Postman

  1. 打开请求 → Authorization 标签页。
  2. 类型:Basic Auth
  3. 输入 UsernamePassword

Postman 会自动构建 Authorization 请求头,并在 Headers 标签页下显示。确保请求 URL 是 https——Postman 会乐意通过 http 发送凭据,但你不应该这样做。

如何在 curl、Postman、fetch 和 Python 中发送 Basic Auth 插图

JavaScript fetch

const credentials = btoa('admin:secret123');
const res = await fetch('https://api.example.com/data', {
  headers: { Authorization: `Basic ${credentials}` },
});

btoa() 在浏览器中运行。在 Node.js 中,请改用 Buffer.from('admin:secret123').toString('base64')

Python requests

import requests

res = requests.get(
    'https://api.example.com/data',
    auth=('admin', 'secret123'),  # requests 会为你构建请求头
)

如何在 curl、Postman、fetch 和 Python 中发送 Basic Auth 插图

Node.js(内置)

const token = Buffer.from('admin:secret123').toString('base64');
const res = await fetch('https://api.example.com/data', {
  headers: { Authorization: `Basic ${token}` },
});

为什么密码正确却返回 401

几乎所有“密码正确但仍然 401”的情况都是以下之一:

  • 使用 echo 而不是 echo -n / printf 导致的尾随换行符。
  • 缺少或小写的 Basic 前缀。
  • 用户名中包含冒号(只有密码可以包含冒号)。
  • 通过 http 发送,代理会剥离该请求头。

使用 printf '%s' 'user:pass' | base64 重新编码并比较。如果服务器持续拒绝有效凭据,请确认它实际上是 401 而不是 403——401 vs 403 解释

常见问题

如何在 curl 中发送 Basic Auth? curl -u username:password https://host,或者设置 -H "Authorization: Basic <token>",其中 token 是 base64(user:pass)

如何在 fetch 中添加 Basic Auth? 设置请求头 Authorization: Basic <btoa('user:pass')>。浏览器 fetch 会忽略放在 URL 中的凭据,因此请显式设置请求头。

为什么我的 Basic Auth 请求在密码正确的情况下失败? 通常是 echo 产生的多余换行符、缺少 Basic 前缀或用户名中的冒号。使用 printf '%s' 'user:pass' | base64 重新编码。

使用 Basic Auth 生成器 构建精确的请求头,并阅读 HTTP Authorization 请求头详解 了解该方案的工作原理。