DEV Community

Cover image for (1) oAuth with Github & Python
schBenedikt
schBenedikt

Posted on • Updated on

(1) oAuth with Github & Python

Hello, this guide is about a simple oAuth platform for Github in a Python code.
It will look like this:
It will look like this

GitHub logo SchBenedikt / oAuth-with-Github-Python

A easy python code how to generate a oAuthentifcation application with Github & Python

Flask GitHub Login

This is a Flask web application that allows users to log in with their GitHub account and view their GitHub projects. It utilizes OAuth authentication with GitHub and retrieves the user's projects using the GitHub API.

Images

image

Features

User Authentication

The application uses the GitHub OAuth flow to authenticate users. Here's how the authentication process works:

  1. When the user accesses the application, they are redirected to the GitHub login page.
  2. After the user logs in with their GitHub account, they are redirected back to the application with an authorization code.
  3. The application exchanges the authorization code for an access token by making a request to GitHub's access token endpoint.
  4. The access token is saved in the user's session for future API requests.

Project Listing

Once the user is authenticated, they can view a list of their GitHub projects. The project listing feature works as follows:

  1. The application…

Generate a oAuth App

Generate oAuth App

Please replace
CLIENT_ID and CLIENT_ID_SECRET with your own keys. The CLIENT_ID_SECRET can be watched only one times.

Please install at first requests, flask and authlib with pip.

Run the code with: py run.py and start the application with visiting http://127.0.0.1:5000/callback

Additionaly infos can be found in the code


import requests
from flask import Flask, redirect, request, session, url_for
from authlib.integrations.flask_client import OAuth # Import the OAuth class

app = Flask(__name__)
app.secret_key = "some_random_string" # Replace the secret key

oauth = OAuth(app)
github = oauth.register(
    name="github",
    client_id="CLIENT_ID",
    client_secret="CLIENT_ID_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("/")
def index():
    # Check if the username is stored in the session
    username = session.get("username")
    if username:
        # Username is stored, display it
        return f"Hello {username}! you're now logged in."
    else:
        # Username is not stored, redirect to the login page
        return redirect(url_for("login"))

@app.route("/login")
def login():
    # Check if the user is already authenticated
    if "access_token" in session:
        # User is already authenticated, redirect to the index page
        return redirect(url_for("index"))

    # User is not authenticated, start the OAuth process
    return github.authorize_redirect(url_for("callback", _external=True))

@app.route("/callback")
def callback():
    # Check if the user is already authenticated
    if "access_token" in session:
        # User is already authenticated, redirect to the index page
        return redirect(url_for("index"))

    # Get the OAuth code from the request
    code = request.args.get("code")

    # Exchange the OAuth code for an access token
    access_token = get_access_token(code)

    # Store the access token in the session
    session["access_token"] = access_token

    # Get the username from the GitHub API
    username = get_username()

    # Store the username in the session
    session["username"] = username

    # Redirect the user to the index page
    return redirect(url_for("index"))

def get_access_token(code):
    # Configure the access token request
    payload = {
        "client_id": "CLIENT_ID",
        "client_secret": "CLIENT_SECRET",
        "code": code,
    }

    headers = {
        "Accept": "application/json",
    }

    # Send the access token request
    response = requests.post(
        "https://github.com/login/oauth/access_token", json=payload, headers=headers
    )

    # Extract the access token from the response
    if response.status_code == 200:
        access_token = response.json()["access_token"]
        return access_token

    # In case of an error, return None
    return None

def get_username():
    access_token = session.get("access_token")

    if access_token:
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Accept": "application/vnd.github.v3+json",
        }

        response = requests.get("https://api.github.com/user", headers=headers)

        if response.status_code == 200:
            username = response.json()["login"]
            return username

    return None

if __name__ == "__main__":
    app.run(debug=True)
Enter fullscreen mode Exit fullscreen mode

And here is the full code without any description

import requests
from flask import Flask, redirect, request, session, url_for
from authlib.integrations.flask_client import OAuth # Import the OAuth class

app = Flask(__name__)
app.secret_key = "some_random_string" # Replace the secret key

oauth = OAuth(app)
github = oauth.register(
    name="github",
    client_id="CLIENT_ID",
    client_secret="CLIENT_ID_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("/")
def index():
    username = session.get("username")
    if username:
        return f"Hello {username}! you're now logged in."
    else:
        return redirect(url_for("login"))

@app.route("/login")
def login():
    if "access_token" in session:
        return redirect(url_for("index"))
    return github.authorize_redirect(url_for("callback", _external=True))

@app.route("/callback")
def callback():
    if "access_token" in session:
        return redirect(url_for("index"))
    code = request.args.get("code")
    access_token = get_access_token(code)
    session["access_token"] = access_token
    username = get_username()
    session["username"] = username
    return redirect(url_for("index"))

def get_access_token(code):
    payload = {
        "client_id": "217973d6a6bd9d3defb9",
        "client_secret": "861b796155a2e5a53ab17e68890e70bbeebadae6",
        "code": code,
    }

    headers = {
        "Accept": "application/json",
    }

    response = requests.post(
        "https://github.com/login/oauth/access_token",
        json=payload,
        headers=headers
    )

    if response.status_code == 200:
        access_token = response.json()["access_token"]
        return access_token

    return None

def get_username():
    access_token = session.get("access_token")

    if access_token:
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Accept": "application/vnd.github.v3+json",
        }

        response = requests.get(
            "https://api.github.com/user",
            headers=headers
        )

        if response.status_code == 200:
            username = response.json()["login"]
            return username

    return None

if __name__ == "__main__":
    app.run(debug=True)

Enter fullscreen mode Exit fullscreen mode

But why I'm doing this?
I try to make an amazing Text-Editor with Github oAuth with many features!

GitHub logo SchBenedikt / Text-Editor

A text editor programmed with Python and PyQt5 with integration to Microsoft Word and Upload-System to Github.

Text-Editor

A text editor programmed with Python and PyQt5 with integration to Microsoft Word.
Read WIKI for full instruction turorial + features

🛫Get started

This repository contains the code for a simple text editor implemented in Python. The text editor allows users to open, save, and export files, as well as apply formatting such as bold, italic, and underline. This post provides instructions on how to test the text editor To test the text editor, follow these steps:

  • ©️lone the repository
    Use the following command to clone the repository to your local machine:
    git clone https://github.com/SchBenedikt/Text-Editor.git

  • ⌨️ Install the dependencies
    Navigate to the cloned repository and install the required dependencies by running the following command:
    pip install -r requirements.txt

  • 🎉 Run the text editor
    Execute the main Python script to launch the text editor application:
    python text_editor.py

The text editor window will open, allowing you to perform various operations…






Write your experiences in the comments!

Top comments (0)