Simon Willison’s Weblog

Subscribe

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.

This is Instant authentication against an existing web application by Simon Willison, posted on 15th July 2004.

Next: Per-site user stylesheets

Previous: PHP 5 is out!

Previously hosted at http://simon.incutio.com/archive/2004/07/15/instant