Python urllib2基本身份验证问题

Sim*_*mon 81 python authentication urllib2

更新:基于Lee的评论我决定将我的代码压缩成一个非常简单的脚本并从命令行运行它:

import urllib2
import sys

username = sys.argv[1]
password = sys.argv[2]
url = sys.argv[3]
print("calling %s with %s:%s\n" % (url, username, password))

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(passman)))

req = urllib2.Request(url)
f = urllib2.urlopen(req)
data = f.read()
print(data)
Run Code Online (Sandbox Code Playgroud)

不幸的是它仍然不会生成Authorization标题(每Wireshark):(

我在通过urllib2发送基本AUTH时遇到问题.我看了一下这篇文章,并按照这个例子.我的代码:

passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, "api.foursquare.com", username, password)
urllib2.install_opener(urllib2.build_opener(urllib2.HTTPBasicAuthHandler(passman)))

req = urllib2.Request("http://api.foursquare.com/v1/user")    
f = urllib2.urlopen(req)
data = f.read()
Run Code Online (Sandbox Code Playgroud)

我通过wireshark在Wire上看到以下内容:

GET /v1/user HTTP/1.1
Host: api.foursquare.com
Connection: close
Accept-Encoding: gzip
User-Agent: Python-urllib/2.5 
Run Code Online (Sandbox Code Playgroud)

您可以看到未通过curl发送请求时发送授权: curl -u user:password http://api.foursquare.com/v1/user

GET /v1/user HTTP/1.1
Authorization: Basic =SNIP=
User-Agent: curl/7.19.4 (universal-apple-darwin10.0) libcurl/7.19.4 OpenSSL/0.9.8k zlib/1.2.3
Host: api.foursquare.com
Accept: */*
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我的代码似乎没有发送身份验证 - 任何人都看到我缺少的东西?

谢谢

-simon

yay*_*wei 197

问题可能是,每个HTTP-Standard的Python库首先发送一个未经身份验证的请求,然后只有在回复401重试时才发送正确的凭据.如果Foursquare服务器不执行"完全标准身份验证",则库将无法运行.

尝试使用标头进行身份验证:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)
Run Code Online (Sandbox Code Playgroud)

遇到了和你一样的问题并从这个帖子中找到了解决方案:http://forums.shopify.com/categories/9/posts/27662

  • 请注意,您可以简单地调用`base64.b64encode`而不是`base64.encodestring`,然后您不需要替换换行符. (3认同)

dno*_*zay 5

(复制粘贴/改编自/sf/answers/1683414071/).

首先,您可以子类化urllib2.BaseHandlerurllib2.HTTPBasicAuthHandler实现,http_request以便每个请求都具有适当的Authorization标头.

import urllib2
import base64

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request
Run Code Online (Sandbox Code Playgroud)

然后,如果你像我一样懒惰,全局安装处理程序

api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"

auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
    realm=None, # default realm.
    uri=api_url,
    user=api_username,
    passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
Run Code Online (Sandbox Code Playgroud)


小智 5

这是我用来处理尝试访问MailChimp的API时遇到的类似问题.这做同样的事情,只是格式化更好.

import urllib2
import base64

chimpConfig = {
    "headers" : {
    "Content-Type": "application/json",
    "Authorization": "Basic " + base64.encodestring("hayden:MYSECRETAPIKEY").replace('\n', '')
    },
    "url": 'https://us12.api.mailchimp.com/3.0/'}

#perform authentication
datas = None
request = urllib2.Request(chimpConfig["url"], datas, chimpConfig["headers"])
result = urllib2.urlopen(request)
Run Code Online (Sandbox Code Playgroud)