首页 > 解决方案 > 基本身份验证返回 401 客户端错误,但在邮递员中工作

问题描述

我已经浏览了许多与使用 Basic Auth 触发 GET 请求相关的类似帖子(例如:Python、HTTPS GET with basic authentication),但仍然无法解决问题。我不断收到错误requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url

使用相同的凭据,标题在邮递员中尝试相同,它按预期工作。验证了 api_key 的 base64encoded 值,password 和 postman 中使用的值完全一样,所以我不认为它的编码或资源访问权限问题。

python -V
Python 3.6.4 :: Anaconda, Inc.

方法一

api_key = 'some_api_key'
password = 'some_password'
headers = {'accept': 'application/json'}

url = 'https://test.access.com/this/url'

api_key_password = "%s:%s" % (api_key, password)

b64_encoded = b64encode(bytes(api_key_password, 'utf-8')).decode("ascii")

headers['authorization'] = 'Basic %s' %  b64_encoded

response = requests.get(url,
                        headers=headers)

if (response.ok):
    json_data = json.loads(response.content)
    print (json_data)
else:
    print (response)
    response.raise_for_status()

方法二

api_key = 'some_api_key'
password = 'some_password'

url = 'https://test.access.com/this/url'

headers = {
    'accept': 'application/json',
}

response = requests.get(url, headers=headers, auth=(api_key, password))
print (response.ok)

if (response.ok):
    json_data = json.loads(response.content)
    print (json_data)
else:
    print (response)
    response.raise_for_status()

你能提供一些指示吗?

标签: pythonpython-requestsbasic-authentication

解决方案


我有一个类似的问题(尽管在 .NET Framework 中)。

就我而言,原因是我最后使用了没有正斜杠的 url,而 API 显然不支持它。

所以https://test.access.com/this/url

抛出 401 错误未经授权

https://test.access.com/this/url/

返回 200 确定。


推荐阅读