Flask App with Authlib for GitHub OAuth

  • Share this:

Code introduction


This code defines a Flask web application using the Authlib library to perform user authentication via GitHub OAuth. It initializes an OAuth client and registers the GitHub provider. The application provides a login page and redirects to the callback URL after user authorization.


Technology Stack : Authlib, Flask

Code Type : Flask Web Application

Code Difficulty : Intermediate


                
                    
from authlib.integrations.flask_client import OAuth
from flask import Flask, redirect, request, session

def create_oauth_client():
    app = Flask(__name__)
    app.secret_key = 'your_secret_key'
    
    # Initialize OAuth client
    oauth = OAuth(app)
    oauth.register(
        name='github',
        client_id='your_github_client_id',
        client_secret='your_github_client_secret',
        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('/login')
    def login():
        return oauth.github.authorize_redirect(redirect_uri='http://localhost:5000/callback')
    
    @app.route('/callback')
    def callback():
        token = oauth.github.authorize_access_token()
        session['oauth_token'] = token['access_token']
        return redirect('/')
    
    return app                
              
Tags: