urllib2是否支持同时返回基本身份验证和摘要身份验证的服务器

2024-05-15 05:12:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是urllib2。 我在登录一个同时返回基本和摘要身份验证的服务器时遇到问题。在

它返回:

WWW-Authenticate: Digest realm="rets@aus.rets.interealty.com",nonce="c068c3d7d30cc0cd80db4d1c599e6d54",opaque="e75078c8-a825-474b-b101-f8ca2d1627ca",qop="auth"
WWW-Authenticate: Basic realm="rets@aus.rets.interealty.com"

我的代码是:

^{pr2}$

我可以使用IE登录这个服务器,而且IE似乎使用了摘要式身份验证。在


Tags: com身份验证wwwurllib2ienoncedigestauthenticate
2条回答

我没有遇到过同样的问题,但有一次我惊讶地发现带有urllib2.HTTPBasicAuthHandler的开场白实际上发出了两个请求,而不是一个:第一个没有身份验证,第二个请求有身份验证。

也就是说,您的案例可能需要三个请求,其中第三个请求可能会忘记来自第二个请求的身份验证—应该检查第二个请求。

您可能应该同时添加:urllib2.HTTPDigestAuthHandler,和{}。

最近我有时间复习这个问题,我想我找到了回答。它有点像pythonurllib2的bug。在urllib2中:

class AbstractDigestAuthHandler:
    def http_error_auth_reqed(self, auth_header, host, req, headers):
        authreq = headers.get(auth_header, None)
        if self.retried > 5:
            # Don't fail endlessly - if we failed once, we'll probably
            # fail a second time. Hm. Unless the Password Manager is
            # prompting for the information. Crap. This isn't great
            # but it's better than the current 'repeat until recursion
            # depth exceeded' approach <wink>
            raise HTTPError(req.get_full_url(), 401, "digest auth failed",
                            headers, None)
        else:
            self.retried += 1
        if authreq:
            scheme = authreq.split()[0]
            if scheme.lower() == 'digest':
                return self.retry_http_digest_auth(req, authreq)

这里的authreq是:

^{pr2}$

在authreq.split()[0]将是“Basic”,它永远不会是“digest”,因此urllib2不会在摘要式身份验证中执行第二个请求。

基本上urllib2假设第一个401响应头中只能有一个身份验证。不幸的是,此服务器返回两种类型的身份验证。

要解决此问题,可以使用基本身份验证,也可以使用其他库,如“请求”。

相关问题 更多 >

    热门问题