【问题标题】:How do I use basic HTTP authentication with the python Requests library?如何在 python Requests 库中使用基本的 HTTP 身份验证?
【发布时间】:2014-11-04 21:34:36
【问题描述】:

我正在尝试在 python 中使用基本的 HTTP 身份验证。我正在使用Requests library

auth = requests.post('http://' + hostname, auth=HTTPBasicAuth(user, password))
request = requests.get('http://' + hostname + '/rest/applications')

响应表单 auth 变量:

<<class 'requests.cookies.RequestsCookieJar'>[<Cookie JSESSIONID=cb10906c6219c07f887dff5312fb for appdynamics/controller>]>
200
CaseInsensitiveDict({'content-encoding': 'gzip', 'x-powered-by': 'JSP/2.2', 'transfer-encoding': 'chunked', 'set-cookie': 'JSESSIONID=cb10906c6219c07f887dff5312fb; Path=/controller; HttpOnly', 'expires': 'Wed, 05 Nov 2014 19:03:37 GMT', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'no-cache', 'cache-control': 'max-age=78000', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html;charset=ISO-8859-1'})

但是当我尝试从不同位置获取数据时, - 我遇到了 401 错误

<<class 'requests.cookies.RequestsCookieJar'>[]>
401
CaseInsensitiveDict({'content-length': '1073', 'x-powered-by': 'Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1.2.2 Java/Oracle Corporation/1.7)', 'expires': 'Thu, 01 Jan 1970 00:00:00 UTC', 'server': 'nginx/1.1.19', 'connection': 'keep-alive', 'pragma': 'No-cache', 'cache-control': 'no-cache', 'date': 'Tue, 04 Nov 2014 21:23:37 GMT', 'content-type': 'text/html', 'www-authenticate': 'Basic realm="controller_realm"'})

据我了解 - 在第二个请求中没有替换会话参数。

【问题讨论】:

  • 您需要包含发出第二个请求的代码
  • 不知道怎么做,也找不到合适的手册
  • 我的意思是,您需要为第二个请求包含 your 代码。通过第二个请求,您指的是“获取”请求吗?

标签: python api python-requests appdynamics


【解决方案1】:

您需要使用session object 并发送身份验证每个请求。该会话还将为您跟踪 cookie:

session = requests.Session()
session.auth = (user, password)

auth = session.post('http://' + hostname)
response = session.get('http://' + hostname + '/rest/applications')

【讨论】:

  • 感谢您的回复,但它也不起作用:(错误与以前相同
  • @oleksii:定义“不起作用”。当您使用 POST(我注意到没有参数)时,服务器是否返回任何令牌或您需要在此处用于 REST API 的任何内容?换句话说,API 文档说明您需要做什么?
  • @Sarit 怎么会这样?请注意,我在答案中链接到官方文档。
  • @MartijnPieters 在第 10 次阅读您的评论后。我还是不明白。我可以在 Postman 中使用 basicAuth。 Postman 会将用户名/密码消化到标题Authorization: Basic &lt;....&gt; 中。但是我无法连接为什么我需要在这里进行会话,但是它可以工作! @oleksii 尝试有什么问题?
  • @Sarit:标头需要包含在您发送到服务器的每个请求中;通常,服务器可以根据存在的标头对您进行身份验证的唯一方法,没有其他信息。将标头添加到每个请求的最简单 方法是使用会话。您没有必须,但是您必须在每个请求中手动包含标头。
【解决方案2】:
import requests

from requests.auth import HTTPBasicAuth
res = requests.post('https://api.github.com/user', verify=False, auth=HTTPBasicAuth('user', 'password'))
print(res)

注意:有时,我们可能会收到 SSL 错误证书验证失败,为避免,我们可以使用verify=False

【讨论】:

  • 为什么验证失败?浏览器访问显示证书已验证。
  • 考虑避免使用verify=False,因为它会使应用容易受到对 https 协议的 MitM 攻击。
  • 赞成使用HTTPBasicAuth 作为身份验证,这就是我想要的。我不会在生产中使用verify=False
  • requests.posts 不适合我,但 requests.get 可以,还有一个更短的版本requests.get(url, auth=(username, password))
【解决方案3】:

在 Python3 中变得容易:

import requests
response = requests.get(uri, auth=(user, password))

【讨论】:

  • 您可能需要额外安装 requests-toolbelt pip install requests-toolbelt
【解决方案4】:

对于python 2:

base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')

request = urllib2.Request(url)

request.add_header("Authorization", "Basic %s" % base64string) 

result = urllib2.urlopen(request)
        data = result.read()

【讨论】:

    【解决方案5】:

    下面一个对我有用

    #!/usr/bin/python3
    import xml.etree.ElementTree as ET
    import requests
    from requests.auth import HTTPBasicAuth
    
    url = 'http://172.25.38.135:600/service/xx/users'      # my URL     
    response = requests.get(url, auth=HTTPBasicAuth('admin', 'adminpass!'))
    
    string_xml = response.content
    tree = ET.fromstring(string_xml)
    ET.dump(tree)
    

    【讨论】:

      【解决方案6】:

      以下对我有用

      from requests.auth import HTTPDigestAuth
      url = 'https://someserver.com'
      requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
      

      【讨论】:

        猜你喜欢
        • 2011-05-08
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-16
        • 2016-07-11
        • 1970-01-01
        相关资源
        最近更新 更多