Twitter Authentication in Django with Tweepy
While working on a recent project during my internship I had to come up with a way to authenticate users in our Django application. We use an Angular front-end that makes calls to Django.
I am going to strip out all the angular magic, but seriously. You need to go check it out. It makes building front-end applications in the browser stupid easy with just a little of javascript know how.
First off go make sure you check out the Tweepy documentation. I found it extremely helpful.
I am assuming you can set up the Django urls.py file yourself. We have at least two routes we need to make.
- Start Twitter Authentication
- Callback from Twitter
In our first view we need to do a few things. We need to set up our twitter application’s consumer token, consumer secret and the callback url.
1auth = tweepy.OAuthHandler('consumer_token', 'consumer_secret', 'callback_url')
This authenticates your application with twitter so you can later authenticate a user. To authenticate a user you need to redirect them to twitter’s website to accept logging into your application. Tweepy has an easy way to get this url using .get_authorization_url(). You should wrap any calls to outside services in try/except because you can never be sure when they will fail because of no fault of your own and when it does you can show a nice error message rather than everything crashing to a halt.
1try:
2 redirect_url = auth.get_authorization_url()
3 except tweedy.TweepError:
4 return HttpResponse('error', status=500)
Your finished view file should look something like this:
1import tweepy
2
3
4def twitterAuthenticate(request):
5 auth = tweepy.OAuthHandler('consumer_token', 'consumer_secret', 'callback_url')
6
7 try:
8 redirect_url = auth.get_authorization_url()
9 except tweepy.TweepError:
10 return HttpResponse('error', status=500)
11
12 request.session['request_token'] = (auth.request_token.key, auth.request_token.secret)
13
14 return HttpResponseRedirect(redirect_url)
15
16def twitterAuthorizeCallback(request):
17 verifier = request.GET.get('oauth_verifier')
18
19 auth = tweepy.OAuthHandler('consumer_token', 'consumer_secret')
20
21 token = request.session.get('request_token')
22 request.session.delete('request_token')
23 auth.set_request_token(token[0], token[1])
24
25 try:
26 token = auth.get_access_token(verifier)
27 except tweepy.TweepError:
28 return HttpResponse('error', status=500)
29
30 response_data = {}
31 response_data['key'] = auth.access_token.key
32 response_data['secret'] = auth.access_token.secret
33
34 response = 'you are now authenticated'
35
36 return HttpResponse(response)