How to create authentication with Flask and Twitter

Nelson Hernández
2 min readSep 1, 2020

In this example we will create a simple authentication using Authlib

1) Creation of virtual environment

In this case I decided to use virtualenv but you can use pipenv if you like.

virtualenv venv
source ./venv/bin/activate

2) Installation of dependencies

pip install Authlib Flask requests python-dotenv

3 ) Flask server creation

from flask import Flask
app = Flask(__name__)
if __name__ == "__main__":
app.run(debug=True)

4 ) Configure Authlib to place our credentials

for this configuration we need a secret_key, if you prefer you can put it in an environment variable since it is secret.

oauth.register () we specify all the Github configurations, I recommend you only put your client_id and client_secret the others are by default.

file app.py

from flask import Flask, url_for, request
from authlib.integrations.flask_client import OAuth, OAuthError
from dotenv import load_dotenv
app = Flask(__name__)
app.secret_key = '!secret'
app.config.from_object('config')
app.secret_key = 'myscretkey'
#configuraciones de oauth
oauth = OAuth(app)
oauth.register(
name='twitter',
api_base_url='https://api.twitter.com/1.1/',
request_token_url='https://api.twitter.com/oauth/request_token',
access_token_url='https://api.twitter.com/oauth/access_token',
authorize_url='https://api.twitter.com/oauth/authenticate',
)
if __name__ == "__main__":
app.run(debug=True)

5) Load environment variables

file config.py

import os
TWITTER_CLIENT_ID = os.getenv('TWITTER_CLIENT_ID')
TWITTER_CLIENT_SECRET = os.getenv('TWITTER_CLIENT_SECRET')

7) File .env

TWITTER_CLIENT_ID=xxxxxxxx
TWITTER_CLIENT_SECRET=xxxxxxxxxxxx

6 ) URL callback creation

We create a route / authorize which will serve to obtain the data of the users who entered their data.

@app.errorhandler(OAuthError)
def handle_error(error):
return error
@app.route('/login')
def login():
redirect_uri = url_for('authorize', _external=True)
return oauth.twitter.authorize_redirect(redirect_uri)
@app.route('/authorize')
def authorize():
token = oauth.twitter.authorize_access_token()
url = 'account/verify_credentials.json'
resp = oauth.twitter.get(url, params={'skip_status': True})
user = resp.json()
print(token)
print(user)
return "successful response"
if __name__ == "__main__":
load_dotenv()
app.run(debug=True)

--

--