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
- Qwen2.5-Coder-32B is an LLM that can code well that runs on my Mac - 12th November 2024
- Visualizing local election results with Datasette, Observable and MapLibre GL - 9th November 2024
- Project: VERDAD - tracking misinformation in radio broadcasts using Gemini 1.5 - 7th November 2024