Posts | Tags | Archive

Gotcha with basic HTTP authentication in Python

When doing basic HTTP authentication in Python, make sure your authentication realm is surrounded by double, NOT single quotes.

Bad:

1
2
3
self.send_response(401)
self.send_header("WWW-Authenticate", "Basic realm='/'")
self.end_headers()

Good:

1
2
3
self.send_response(401)
self.send_header("WWW-Authenticate", "Basic realm=\"/\"")
self.end_headers()

The single quotes work with most browsers, curl, wget, and tons of other tools. However, when using Python to access the page (using urllib2.HTTPPasswordMgrWithDefaultRealm to manage authentication) single quotes don't trigger the "automatic retry with authentication" response, and instead just raise a 401 HTTPError.

© Carey Metcalfe. Built using Pelican. Theme is subtle by Carey Metcalfe. Based on svbhack by Giulio Fidente.