all Python 3urllib.requestterm
urllib.request.HTTPDigestAuthHandler
authentication
Answers a 401 with WWW-Authenticate: Digest by repeating the request with a hashed response to the server challenge.
Syntax
urllib.request.HTTPDigestAuthHandler(password_mgr=None)
If an opener has both it and HTTPBasicAuthHandler, Digest is tried first — its handler_order is 490 against Basic's 500; on another 40x Basic gets its turn. For a challenge with any scheme other than Digest and Basic it raises ValueError. The password is hashed, but MD5 is weak — still send the data over HTTPS.
Examples
import email.message, io, urllib.error, urllib.request, urllib.response
def reply(req, code, body=b'', **headers):
msg = email.message.Message()
for name, value in headers.items():
msg[name.replace('_', '-')] = value
resp = urllib.response.addinfourl(io.BytesIO(body), msg, req.full_url, code)
resp.msg = 'demo'
return resp
class Server(urllib.request.BaseHandler):
handler_order = 100
def http_open(self, req):
auth = req.get_header('Authorization')
if auth:
print(auth[:17]) # → Digest username="
return reply(req, 200, b'ok')
return reply(req, 401, WWW_Authenticate='Digest realm="api", nonce="n1", qop="auth"')
mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
mgr.add_password(None, 'http://example.com/', 'u', 'p')
opener = urllib.request.build_opener(Server, urllib.request.HTTPDigestAuthHandler(mgr))
print(opener.open('http://example.com/').read()) # → b'ok'
import urllib.request
print(urllib.request.HTTPDigestAuthHandler.handler_order,
urllib.request.HTTPBasicAuthHandler.handler_order) # → 490 500
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy