做前端或者调用接口的时候,经常遇到需要登录才能访问的接口。这时候服务器会要求你在请求头里带上认证信息,最常见的就是 Authorization 字段。别看它就一行配置,搞不定还真拿不到数据。
Authorization 是干什么的?
简单说,它就是告诉服务器“我是谁”的凭证。比如你登录了某个网站,后台给你返回一个 token,之后每次请求都得把这个 token 放在 Authorization 头里,服务器一看就知道你是合法用户。
常见格式:Bearer Token
现在大多数 API 都用 Bearer 认证方式。格式是:
Authorization: Bearer <your-token-here>
比如你的 token 是 abc123xyz,那请求头就要写成:
Authorization: Bearer abc123xyz
代码里怎么加?
以 JavaScript 的 fetch 为例,如果你要调用一个需要认证的接口:
fetch('https://api.example.com/user', {
method: 'GET',
headers: {
'Authorization': 'Bearer abc123xyz',
'Content-Type': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data));
Python 用 requests 库也差不多:
import requests
headers = {
'Authorization': 'Bearer abc123xyz'
}
response = requests.get('https://api.example.com/user', headers=headers)
print(response.json())
除了 Bearer,还有别的类型吗?
有。比如早期用的 Basic 认证,它是把用户名和密码拼成 username:password 然后做 base64 编码:
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
这种现在用得少了,主要出现在一些内部系统或老旧服务中。
浏览器里怎么看这个头?
打开开发者工具,切换到 Network 标签,随便点一个请求,看 Headers 部分有没有 Authorization。有些敏感接口这个字段会被隐藏,但一般能看到存在这个头。
注意事项
token 别硬编码在代码里,尤其是前端。万一被扒走,别人就能冒充你操作账号。测试时可以用,上线前记得换成安全的方式获取和存储。
另外,拼写别错了,是 Authorization,不是 Authorizaton 或者 Authrization,少个字母就 401 了。