事倍功半是蠢蛋 12 Oauth2.0第三方登陆急速入门(以github/gitee为例子)

一个人必须要等到他学会了 往往才能找到合适的教程。
我觉得我似乎浪费了很多时间,还是说这仅仅是知识魔咒,沉淀是必要的?
我最近在看钱学森的工程控制论跟论系统工程,希望能有所启发,做到事半功倍。

使用github文档和流程图学习基础概念
https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps

使用这个项目快速入门github例子,实现github第三方登陆,代码如下
https://github.com/radioli/github-oauth2-example-flow/blob/main/main.py

import requests
from urllib.parse import urlencode
from flask import Flask, redirect, request


github_client_id = ''
github_client_secret = ''

# This is the URL we'll send the user to first to get their authorization
authorize_url = 'https://github.com/login/oauth/authorize'

# This is the endpoint our server will request an access token from
token_url = 'https://github.com/login/oauth/access_token'

# This is the Github base URL we can use to make authenticated API requests
api_url_base = 'https://api.github.com/'

# The URL for this script, used as the redirect URL

redirect_url = 'http://127.0.0.1:8080/redirect'

# The code returned by github from #GET /login/oauth/authorize

payload = {"response_type": "code", 'client_id': github_client_id,
           'redirect_uri': redirect_url, 'scope': 'repo'}


def provide_token_payload(code):
    return {'grant_type': 'authorization_code', 'client_id': github_client_id,
            'client_secret': github_client_secret, 'redirect_uri': redirect_url, 'code': code}


app = Flask(__name__)


@app.route("/")
def index():
    auth_req = authorize_url+'?'+urlencode(payload)
    return redirect(auth_req)


@app.route("/redirect")
def redirect_github_url():
    code = request.args['code']
    print(code)
    print(provide_token_payload(code))
    resp = requests.post(token_url, provide_token_payload(code)).text
    return resp


if __name__ == "__main__":
    app.run(host="127.0.0.1", port=8080, debug=True)

gitee同理
先获取token:https://docs.authing.co/v2/guides/connections/social/gitee/
以下是demo,我用Ai生成的
pip 安装flask直接就能用

from flask import Flask, redirect, request, session, jsonify
import requests

app = Flask(__name__)
app.secret_key = "your_secret_key"  # 替换为一个安全的密钥

# Gitee OAuth 配置
CLIENT_ID = "啊倒萨大大撒大苏打"  # 替换为你的 Gitee 应用的 Client ID
CLIENT_SECRET = "去问我去我去饿饿我去饿饿我去饿"  # 替换为你的 Gitee 应用的 Client Secret
REDIRECT_URI = "http://127.0.0.1:8000/callback"
AUTHORIZATION_URL = "https://gitee.com/oauth/authorize"
TOKEN_URL = "https://gitee.com/oauth/token"
USER_INFO_URL = "https://gitee.com/api/v5/user"

@app.route("/")
def index():
    return """
    <h1>Gitee OAuth2 登录示例</h1>
    <a href="/login"><button>登录 Gitee</button></a>
    """

@app.route("/login")
def login():
    # 构造授权 URL 并跳转到 Gitee 登录页面
    authorization_url = f"{AUTHORIZATION_URL}?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code"
    return redirect(authorization_url)

@app.route("/callback")
def callback():
    # 获取授权码 (code)
    code = request.args.get("code")
    if not code:
        return "Error: No code provided", 400

    # 使用授权码获取访问令牌 (access_token)
    token_data = {
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "code": code,
        "grant_type": "authorization_code",
        "redirect_uri": REDIRECT_URI,
    }
    response = requests.post(TOKEN_URL, data=token_data)
    token_info = response.json()
    access_token = token_info.get("access_token")

    if not access_token:
        return f"Error: {token_info}", 400

    # 使用 access_token 获取用户信息
    headers = {"Authorization": f"Bearer {access_token}"}
    user_response = requests.get(USER_INFO_URL, headers=headers)
    user_info = user_response.json()

    # 存储用户信息到 session
    session["user"] = user_info
    stra = str(user_info)
    return f"""
    <h1>登录成功!</h1>
    <p>用户名: {user_info['login']}</p>
    <p>邮箱: {stra}</p>
    <a href="/logout"><button>退出登录</button></a>
    """

@app.route("/logout")
def logout():
    # 清除 session 中的用户信息
    session.pop("user", None)
    return redirect("/")

@app.route("/user")
def get_user():
    # 返回当前登录用户的 JSON 数据
    user = session.get("user")
    if user:
        return jsonify(user)
    else:
        return jsonify({"error": "用户未登录"}), 401

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

配置第三方oauth
github:点主页头像=> setting齿轮图标=>最底下Developer Settings =>oauth
gitee:点主页头像=> 设置=>数据管理下的第三方应用=>oauth创建应用

posted @ 2025-03-25 10:56  空心橙子  阅读(20)  评论(0)    收藏  举报