Skip to content

A Simple Django WebAuth Decorator

Like many universities, my employer uses Stanford’s WebAuth Single Sign-On package as one major piece in it’s computing account system. WebAuth is an MIT licensed infrastructure that allows decentralized web applications to securely authenticate users without themselves ever handling user credentials. Websites begin by sending unauthenticated users to a trusted WebAuth server which validates the user and provides them with a ticket which is passed back to the application. The application web server then communicates directly with the WebAuth server to validate the ticket it was given. If the ticket is valid, the application is provided with information on the user, and it can proceed without further interaction with the server. As long as the user’s WebAuth session remains active, any other application the user visits can authenticate the user behind the scenes.

The benefits to users of a consistent security interface are significant, so I’ve recently been pushing myself to make use of WebAuth where possible. Unfortunately, there’s not a lot of preexisting code for integrating WebAuth into mainstream web frameworks, so I’ve had to write my own, which — fortunately for me — hasn’t proven to be all that difficult. Today I’m going to share a snippet of code that I wrote to integrate WebAuth into a Django app:

webauth.py — Pretty Print HTML

webauth.py — Raw Code

@webauth_required is a Python decorator that functions similarly to the @login_required decorator that is provided with Django. Importing this decorator and prepending a view function with @webauth_required is all that’s needed to force that view to authenticate the user. Once they’re authenticated, their username is stored in a Django session for authorization purposes (as ‘netid’ in this code, since that’s the parlance familiar with users and developers on my campus). Obviously the WebAuth endpoint (AUTH_URL) is also specific to my situation, and most WebAuth providers will require registration of client applications to enhance security.

The only thing that’s left is to provide a logout mechanism. My logout view (one of the few views that doesn’t need the @webauth_required decorator in my app!) simply destroys the session data and provides the user with a link to log out of WebAuth entirely; it’s possible for the user to log out of the app but remain logged in to WebAuth, which effectively leaves them logged into the app (since they’ll be re-authenticated behind the scenes if they return), but that’s how the powers that be have asked client apps to behave, so that’s how it is.

Categories: Random.

Tags: , , , , ,

Comment Feed

No Responses (yet)



Some HTML is OK

or, reply to this post via trackback.