Instant authentication against an existing web application
15th July 2004
I was thinking today about the problem of querying an existing authentication database from a new application—exactly the kind of thing web services are useful for. Then I realised that any web application protected by HTTP Basic authentication already provides a standard API against which queries can be run. Here’s the Python code to do exactly that:
def auth_against_url(url, username, password):
import urllib2, base64
request = urllib2.Request(url)
b64 = base64.encodestring('%s:%s' % (username, password))[:-1]
request.add_header('Authorization', 'Basic %s' % b64)
try:
urllib2.urlopen(request)
except urllib2.HTTPError:
return False
return True
To check a username and password against an existing application’s user database, just call the above function with the URL of a page within the existing application as the first argument. The function returns True if the username and password are valid, and False otherwise. It doesn’t get much simpler than that.
A nice side effect of using Python’s standard library modules is that they transparently support HTTPS, so authentication can take place over an encrypted channel provided the target application supports it.
More recent articles
- My AI/LLM predictions for the next 1, 3 and 6 years, for Oxide and Friends - 10th January 2025
- Weeknotes: Starting 2025 a little slow - 4th January 2025
- I still don't think companies serve you ads based on spying through your microphone - 2nd January 2025