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 use Twitter 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.
# 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' )
@app.route('/') defindex(): access_token = session.get('access_token') if access_token isNone: return redirect(url_for('login'))
access_token = access_token[0]
return render_template('index.html')
@app.route('/login') deflogin(): return twitter.authorize(callback=url_for('oauth_authorized', next=request.args.get('next') or request.referrer orNone))
@app.route('/logout') deflogout(): 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 defoauth_authorized(resp): next_url = request.args.get('next') or url_for('index') if resp isNone: flash(u'You denied the request to sign in.') return redirect(next_url)
Leave a Reply: