Using OpenID, OAuth, OAuth2 and OpenID+OAuth

Over the last year I’ve had an authentication library that I’ve used to slice and dice public services and like most things it’s collected more than it’s share of dust, cruft and other ugly appendages that you wonder if it’ll work then next time you use it.  I’ve been hot and heavy over django (even if it’s embedded inside of Tornado) as a general framework for a while, it’s not broke don’t fix it…

The general case of site authentication looks like this:

  • You need your own username + password
  • You’re perfectly willing to give it all to Facebok/Google/etc. to handle

Depeding on the project I’m quite happy with giving it away, but there are times when you want to have “ownership” of the users on your website.  In which case in this day and age it’s important to allow people to associate their well known credentials with your service — cool.  FYI – This is my “new favorite flow”

  • Ask for email + password + (any service required fields – screen name ….)
  • Require them to associate with  another service
    • Capture picture / full name and other bits from “Facebook”
  • Follow up with prompting to finish profile or other service specific tasks

That’s the simple part, the hard part has been dealing with OpenID, OAuth, OAuth2 and Hybrid protocols.   Since very rarely do you want just to get the fine photo for the user and forget about it.  You probably want to do one of these things:

  • Tweet something they did
  • Check in
  • Add to their facebook page
  • Scrape their friends
  • …etc…

Which means you need to store a token, not only that but some of these wonderful protocols don’t give you persistant identifiers.   Anyway, here’s a bit of commentary and some code excerpts for you to review, hopefully my refactorization makes life more interesting moving forward and those hulking if statements I used to have are gone.

OAuth — The big challenge is that the token you get is a transient identifier, it will change if you assocate account information with this your doomed.   So, typically what you end up needing to do is take your OAuth token and go back and pull the profile, which of course means that you need yet another round trip behind the scenes to get an authentication to happen.

 1
 2class GowallaBackend(OpenBackend) :
 3    name = gowalla
 4    info = settings.OPENAUTH_DATA.get(name, {})
 5
 6    def prompt(self) :
 7        return https://api.gowalla.com/api/oauth/new?%s % urllib.urlencode({
 8            client_id : self.key,
 9            redirect_uri : self.return_to,
10        })
11
12    def get_access_token(self) :
13        url = https://api.gowalla.com/api/oauth/token
14        body = {
15            client_id : self.key,
16            client_secret : self.secret,
17            redirect_uri : self.return_to,
18            code : self.request.GET[code],
19            grant_type : authorization_code,
20        }
21
22        data = self._fetch(url, postdata=body, headers={Accept:application/json})
23
24        vals = json.loads(data)
25
26        return OpenToken(vals[access_token])
27
28    def get_profile(self, token) :
29        from ..libs.gowalla import Gowalla
30
31        go = Gowalla(self.key, access_token=token.token)
32
33        profile = go.user_me()
34
35        identity = "gowalla:%s" % profile[url]
36
37        return identity, {
38            first_name : profile[first_name],
39            last_name : profile[last_name],
40            email : None,
41        }, profile

OAuth+OpenID — This is where life gets a bit more painful…  Typically over getting all of the URI bits worked out, where things go etc.  We won’t mention strange things like Yahoo doesn’t return the oauth token when asked unless you’ve approved yourself for non-public information…  Gack!

 1class GoogleBackend(OpenBackend) :
 2    name = google
 3    info = settings.OPENAUTH_DATA.get(name,{})
 4
 5    def _get_client(self) :
 6        client = consumer.Consumer(self.request.session, util.OpenIDStore())
 7        client.setAssociationPreference([(HMAC-SHA1, no-encryption)])
 8        return client
 9
10    def prompt(self) :
11        client = self._get_client()
12
13        auth_request = client.begin(https://www.google.com/accounts/o8/id)
14
15        auth_request.addExtensionArg(http://openid.net/srv/ax/1.0, mode, fetch_request)
16        auth_request.addExtensionArg(http://openid.net/srv/ax/1.0, required, email,firstname,lastname)
17        auth_request.addExtensionArg(http://openid.net/srv/ax/1.0, type.email, http://schema.openid.net/contact/email)
18        auth_request.addExtensionArg(http://openid.net/srv/ax/1.0, type.firstname, http://axschema.org/namePerson/first)
19        auth_request.addExtensionArg(http://openid.net/srv/ax/1.0, type.lastname, http://axschema.org/namePerson/last)
20
21        auth_request.addExtensionArg(http://specs.openid.net/extensions/oauth/1.0, consumer, self.key)
22        auth_request.addExtensionArg(http://specs.openid.net/extensions/oauth/1.0, scope, http://www.google.com/m8/feeds)
23
24        parts = list(urlparse.urlparse(self.return_to))
25        realm = urlparse.urlunparse(parts[0:2] + [] * 4)
26
27        return auth_request.redirectURL(realm, self.return_to)
28
29    def get_access_token(self) :
30        if self.request.GET.get(openid.mode, None) == cancel or self.request.GET.get(openid.mode, None) != id_res :
31            raise OpenBackendDeclineException()
32
33        client = self._get_client()
34        auth_response = client.complete(self.request.GET, self.return_to)
35
36        if isinstance(auth_response, consumer.FailureResponse) :
37            raise OpenBackendDeclineException("%s" % auth_response)
38
39        ax = auth_response.extensionResponse(http://openid.net/srv/ax/1.0, True)
40
41        self.email = ax.get(value.email,)
42        self.first_name = ax.get(value.firstname,)
43        self.last_name = ax.get(value.lastname,)
44
45        self.identity = auth_response.getSigned(openid.message.OPENID2_NS, identity, None)
46
47        otoken = auth_response.extensionResponse(http://specs.openid.net/extensions/oauth/1.0, True)
48        oclient = GoogleOAuthClient(self.key, self.secret)
49
50        tok = oclient.get_access_token(otoken[request_token])
51        return OpenToken(tok[oauth_token], tok[oauth_token_secret])
52
53    def get_profile(self, token) :
54        v = {
55            email : self.email,
56            first_name : self.first_name,
57            last_name : self.last_name,
58        }
59        return self.identity, v, v