python oauth与github
#python #github #oauth

您好,本指南是关于python代码中GitHub的简单OAuth平台。
看起来像这样:
It will look like this

生成一个oauth应用

Generate oAuth App

请更换
client_id and Client_id_secret带有您自己的密钥。 client_id_secret只能观看一次。

请在requestsflaskauthlib时安装 with pip

使用:py run.py运行代码,并使用访问http://127.0.0.1:5000/callback

启动应用程序

额外的信息可以在代码中找到


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": "217973d6a6bd9d3defb9",
        "client_secret": "861b796155a2e5a53ab17e68890e70bbeebadae6",
        "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)

在评论中写下您的经验!