DEV Community

Cover image for Authentication with Flask and GitHub | Authlib
Nelson Hernández
Nelson Hernández

Posted on • Edited on

6 1

Authentication with Flask and GitHub | Authlib

For this example we will use Authlib which is the ultimate Python library in building OAuth and OpenID Connect servers

Installation



pip3 install Flask Authlib requests python-dotenv

Enter fullscreen mode Exit fullscreen mode




Configuration




from flask import Flask, url_for, redirect
from dotenv import load_dotenv
from os import getenv
from authlib.integrations.flask_client import OAuth

app = Flask(name)

app.secret_key = "mysecretkey"

oauth = OAuth(app)

github = oauth.register(
name='github',
client_id=getenv("CLIENT_ID"),
client_secret=getenv("SECRET_ID"),
access_token_url='https://github.com/login/oauth/access_token',
access_token_params=None,
authorize_url='https://github.com/login/oauth/authorize',
authorize_params=None,
api_base_url='https://api.github.com/',
client_kwargs={'scope': 'user:email'},
)

@app.route("/")
def saludo():
return "Hello"

if name == 'main':
load_dotenv()
app.run(debug=True, port=4000, host="0.0.0.0")

Enter fullscreen mode Exit fullscreen mode




Route for Authorization

authorize_redirect indicates the url to redirect to the "Callback URL"



@app.route("/login")
def login():
redirect_url = url_for("authorize", _external=True)
return github.authorize_redirect(redirect_url)

Enter fullscreen mode Exit fullscreen mode




Callback URL




@app.route("/authorize")
def authorize():
token = github.authorize_access_token()
resp = github.get('user', token=token)
profile = resp.json()
# do something with the token and profile
print(profile, token)
return redirect('/')

Enter fullscreen mode Exit fullscreen mode




Settings in GitHub

OAuth application settings

Code of example in GitHub 🔗

Image of Stellar post

🚀 Stellar Dev Diaries Series: Episode 1 is LIVE!

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (1)

Collapse
 
dkudrik profile image
Denis

@nelsoncode hello, could you please explain how to log out(revoke acces token)?

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay