Monday, 2 July 2012

Using Twitter As Your Flask Login Provider in 6 Lines

First off, I lied about the 6 lines, but it got you here and now you can see how simple it is yourself. There are actually 40 lines I think.

When I was building Flask Ahoy! I wanted to use Twitter as the login provider. I could spend a while boring you about why (as opposed to say Google, Facebook, OpenID or Roll-Your-Own), but I'l save that for another exciting post.

I have used the extremely handy Flask-OAuth to do all the legwork so you need to install that:

Next we need some html for users to click on to sign in and sign out. Try this simple block :

Next the real code begins. In your views module you need three views:

  • One to send you off to Twitter to get authorized (login)
  • One to get the callback from Twitter and store your authorization credentials (twitter_authorized)
  • One to log you out and tidy up (logout)

Finally we need a special little method which remembers your credentials:


Now for the sake of safety I'm going to point out a couple of things here:

  • This scenario uses flask sessions (encrypted cookies) to store your Twitter OAuth token.
  • When you logout, you are only destroying the twitter_user flag, you should probably destroy your credentials as well.


Good luck fellow travelers.

6 comments:

  1. flask sessions are only signed, not encrypted, you shouldn't be storing oauth tokens there unless you flip over to an actual encrypted serialization

    ReplyDelete
  2. Quite right.

    You could i suppose just encrypt in the twitter_authorized and decrypt in get_twitter_oauth_token using the flask secret. More lines.

    ReplyDelete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. So... twitter_factory...

    Where does that come from? It looks like it has lots of shiny things, but neither Google nor Github are turning up anything.

    ReplyDelete
  5. ryepdx - best way is just to show you -

    Have a look at https://gist.github.com/4085206

    ReplyDelete
  6. Could you please post the full code in one place, including all imports. Thanks

    ReplyDelete