logo

Login to Flask App with Twitter

In this tutorial you will learn how to use Twitter for login authentication in a Flask app. Instead of using a custom user login system, you could useTwitter to authenticate with your website. Your visitors may already have an account on Twitter, so why not use it to login?

To do so, we use a protocol called OAuth. From wikipedia:

OAuth is a protocol that utilizes tokens in order to access resources on behalf of a resource owner. Think giving a user the ability to give out a valet key to certain portions of your site. Many sites, such as Google, Facebook, and Twitter use OAuth for authenticating third party clients in order to access certain user resources.

Don’t worry if that sounds vague, we’ll take you through the steps.

Related course
Python Flask: Make Web Apps with Python

Twitter login, Flask


Get the twitter consumer_key and consumer_secret

Go to https://apps.twitter.com/ and create a new app.

twitter_create_app Twitter create app

Specify your app details:

twitter_create_app2 twitter_create_app2

You will then see this screen:

flask_screen twitter flask_screen twitter

Press Keys and Access Tokens. Finally you will see your consumer_key and consumer_secret which you will need for your app.

twitter_consumer_key twitter_consumer_key

The code
Create the file app.py and set your consumer_key and consumer_secret that you got from twitter.

from flask import Flask, request, redirect, url_for, session, g, flash, \
render_template
from flask_oauth import OAuth

from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base

# configuration
SECRET_KEY = 'development key'
DEBUG = True

# setup flask
app = Flask(__name__)
app.debug = DEBUG
app.secret_key = SECRET_KEY
oauth = OAuth()

# Use Twitter as example remote application
twitter = oauth.remote_app('twitter',
# unless absolute urls are used to make requests, this will be added
# before all URLs. This is also true for request_token_url and others.
base_url='https://api.twitter.com/1/',
# where flask should look for new request tokens
request_token_url='https://api.twitter.com/oauth/request_token',
# where flask should exchange the token with the remote application
access_token_url='https://api.twitter.com/oauth/access_token',
# twitter knows two authorizatiom URLs. /authorize and /authenticate.
# they mostly work the same, but for sign on /authenticate is
# expected because this will give the user a slightly different
# user interface on the twitter side.
authorize_url='https://api.twitter.com/oauth/authenticate',
# the consumer keys from the twitter application registry.
consumer_key='ADD TWITTER CONSUMER KEY',
consumer_secret='ADD TWITTER CONSUMER SECRET'
)

@twitter.tokengetter
def get_twitter_token(token=None):
return session.get('twitter_token')

@app.route('/')
def index():
access_token = session.get('access_token')
if access_token is None:
return redirect(url_for('login'))

access_token = access_token[0]

return render_template('index.html')

@app.route('/login')
def login():
return twitter.authorize(callback=url_for('oauth_authorized',
next=request.args.get('next') or request.referrer or None))

@app.route('/logout')
def logout():
session.pop('screen_name', None)
flash('You were signed out')
return redirect(request.referrer or url_for('index'))

@app.route('/oauth-authorized')
@twitter.authorized_handler
def oauth_authorized(resp):
next_url = request.args.get('next') or url_for('index')
if resp is None:
flash(u'You denied the request to sign in.')
return redirect(next_url)

access_token = resp['oauth_token']
session['access_token'] = access_token
session['screen_name'] = resp['screen_name']

session['twitter_token'] = (
resp['oauth_token'],
resp['oauth_token_secret']
)

return redirect(url_for('index'))

if __name__ == '__main__':
app.run()

Create the directory /templates/ with the file index.html

{% block body %}
<h2>Flask Login App</h2>
&#123;% if session['screen_name'] %&#125;
Hello &#123; &#123; session['screen_name'] &#125;&#125;!
&#123;% else %&#125;

Sign in with twitter.

<a href="&#123; &#123; url_for('login') &#125;&#125;"><img src="&#123; &#123;
url_for('static', filename='sign-in.png') &#125;&#125; alt="sign in"></a>
&#123;% endif %&#125;
&#123;% endblock %&#125;

Finally create the directory /static/ with the image sign-in.png:

sign-in

Start your app with:

python app.py

Open the app in your web-browser. Then your users can simply follow the steps to login:

Flask Login Twitter Flask Login Twitter Screen Flask OAuth Twitter Flask OAuth Twitter twitter_oauth twitter_oauth