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

Swift Package Manager And How To Cache It With CI

Admin has the power cybertalents challenge solving writeup

A guide for Placement-Preparation in Product-based Companies

AERGO JDBC Release

Shadowing or how to fix: loop variable i captured by func literal

Intentional Product Development: Managing Externalities of Productivity Software

Data Structures — Stack, Last In First Out

Android App Architecture: Domain layer

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

FLASK FRAMEWORK

How to set up a Project in Django

Simple REST API application using Flask

User Auth with REST API in Django — Part 1