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

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 🔗

Top comments (1)

Collapse
 
dkudrik profile image
Denis

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