实现自定义 Python 身份验证处理程序
题
答案是 上一个问题 表明 Nexus 实现了 自定义身份验证助手 称为“NxBASIC”。
我如何开始在 python 中实现处理程序?
更新:
按照 Alex 的建议实现处理程序似乎是正确的方法,但尝试从 authreq 中提取方案和领域失败。authreq 的返回值为:
str: NxBASIC realm="Sonatype Nexus Repository Manager API""
AbstractBasicAuthHandler.rx.search(authreq) 仅返回单个元组:
tuple: ('NxBASIC', '"', 'Sonatype Nexus Repository Manager API')
所以scheme,realm = mo.groups()失败了。从我有限的正则表达式知识看来,AbstractBasicAuthHandler 中的标准正则表达式应该匹配方案和领域,但似乎并非如此。
正则表达式是:
rx = re.compile('(?:.*,)*[ \t]*([^ \t]+)[ \t]+'
'realm=(["\'])(.*?)\\2', re.I)
更新2:从AbstractBasicAuthHandler的检查来看,默认的处理是:
scheme, quote, realm = mo.groups()
更改为这个有效。我现在只需要针对正确的领域设置密码。谢谢亚历克斯!
解决方案
如果,如上所述,名称和描述是这个“NxBasic”和旧的“Basic”之间的唯一区别,那么您基本上可以从 urllib2.py 中复制粘贴编辑一些代码(不幸的是,它没有将方案名称公开为本身很容易被覆盖),如下(参见 urllib2.py的在线资源):
import urllib2
class HTTPNxBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
def http_error_auth_reqed(self, authreq, host, req, headers):
# host may be an authority (without userinfo) or a URL with an
# authority
# XXX could be multiple headers
authreq = headers.get(authreq, None)
if authreq:
mo = AbstractBasicAuthHandler.rx.search(authreq)
if mo:
scheme, realm = mo.groups()
if scheme.lower() == 'nxbasic':
return self.retry_http_basic_auth(host, req, realm)
def retry_http_basic_auth(self, host, req, realm):
user, pw = self.passwd.find_user_password(realm, host)
if pw is not None:
raw = "%s:%s" % (user, pw)
auth = 'NxBasic %s' % base64.b64encode(raw).strip()
if req.headers.get(self.auth_header, None) == auth:
return None
req.add_header(self.auth_header, auth)
return self.parent.open(req)
else:
return None
通过检查您可以看到,我刚刚将 urrlib2.py 中的两个字符串从“Basic”更改为“NxBasic”(以及小写等效项)(在 http basic auth handler 类的抽象 basic auth handler 超类中) 。
尝试使用这个版本——如果它仍然不起作用,至少让它成为你的代码可以帮助你添加打印/日志语句、断点等,以更好地理解什么是破坏的以及如何破坏的。祝你好运!(抱歉,我无法提供更多帮助,但我没有任何 Nexus 可供实验)。
不隶属于 StackOverflow