urllib2是否支持抢占式身份验证身份验证? [英] does urllib2 support preemptive authentication authentication?

查看:208
本文介绍了urllib2是否支持抢占式身份验证身份验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问REST API。

I am trying access a REST API.

我可以在Curl / REST Client(UI工具)中使用它,并启用了抢先身份验证。

I can get it working in Curl/REST Client (the UI tool), with preemptive authentication enabled.

但是,使用urllib2,默认情况下它似乎不支持这个,我找不到打开它的方法。

But, using urllib2, it doesn't seem to support this by default and I can't find a way to turn it on.

谢谢:)

推荐答案

这是一个简单的抢占式HTTP基本身份验证处理程序,基于<$ c的代码$ C> urllib2.HTTPBasicAuthHandler 。它可以以完全相同的方式使用,除了授权标头将添加到每个带有匹配URL的请求。请注意,此处理程序应与 HTTPPasswordMgrWithDefaultRealm 一起使用。那是因为你没有领先于 WWW-Authenticate 挑战,因为你是先发制人的。

Here's a simple Preemptive HTTP basic auth handler, based on the code from urllib2.HTTPBasicAuthHandler. It can be used in the exact same manner, except an Authorization header will be added to every request with a matching URL. Note that this handler should be used with a HTTPPasswordMgrWithDefaultRealm. That's because there is no realm coming back in a WWW-Authenticate challenge since you're being preemptive.

class PreemptiveBasicAuthHandler(urllib2.BaseHandler):

        def __init__(self, password_mgr=None):
                if password_mgr is None:
                        password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
                self.passwd = password_mgr
                self.add_password = self.passwd.add_password

        def http_request(self,req):
                uri = req.get_full_url()
                user, pw = self.passwd.find_user_password(None,uri)
                #logging.debug('ADDING REQUEST HEADER for uri (%s): %s:%s',uri,user,pw)
                if pw is None: return req

                raw = "%s:%s" % (user, pw)
                auth = 'Basic %s' % base64.b64encode(raw).strip()
                req.add_unredirected_header('Authorization', auth)
                return req

这篇关于urllib2是否支持抢占式身份验证身份验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆