DEV Community

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

Posted on • Updated on


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


pip3 install Flask Authlib requests python-dotenv
Enter fullscreen mode Exit fullscreen mode


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(
    client_kwargs={'scope': 'user:email'},

def saludo():
    return "Hello"

if __name__ == '__main__':
    load_dotenv(), port=4000, host="")
Enter fullscreen mode Exit fullscreen mode

Route for Authorization

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

def login():
    redirect_url = url_for("authorize", _external=True)
    return github.authorize_redirect(redirect_url)
Enter fullscreen mode Exit fullscreen mode

Callback URL

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 🔗

Top comments (1)

dkudrik profile image

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

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.