How to create authentication with Flask and Twitter

1) Creation of virtual environment

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

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

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

6 ) URL callback creation

@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)

Frontend Developer and Content Creator from El Salvador

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

SRE/DevOps Interview Questions — Tooling — Part 1

Becoming a “Super” Full-stack Web Developer in Modern Expectations — Tough but not Impossible

Configurable frontend apps with docker and env-serve

Viral GSA Search Engine Ranker VPS

Flutter: Firebase GitHub Authentication

The Truth On Trump’s Recent Firing Of My Father

Automation Is Fun With Ansible

Android APPS — Design, Develop, Distribute

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nelson Hernández

Nelson Hernández

Frontend Developer and Content Creator from El Salvador

More from Medium

PyBlog — Project Structure

CRUD operation in MongoDB using flask

Fun Personality check with REST API in 7 minutes.

Multiprocessing — Simple Guide to Create Processes and Pool of Processes in Python