You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python脚本中处理OAuth 2.0重定向后的授权码获取

本地无缝实现OAuth 2.0授权码流程(Python)

给你两个简洁的本地实现方案,完全避免手动复制授权码,适配内部使用场景:

方案一:纯标准库实现(无额外依赖)

用Python内置的http.server配合后台线程,轻量且无需安装第三方包:

import http.server
import threading
import webbrowser
from urllib.parse import urlparse, parse_qs
import requests

# 全局变量存储授权码
AUTH_CODE = None
# 本地回调端口,需和OAuth服务商注册的重定向URI一致
PORT = 8080
REDIRECT_URI = f"http://localhost:{PORT}/callback"

# OAuth服务商配置(替换成你的实际参数)
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
AUTHORIZE_URL = "https://oauth-provider.com/authorize"
TOKEN_URL = "https://oauth-provider.com/token"
SCOPE = "read write"

class OAuthCallbackHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        global AUTH_CODE
        # 解析请求路径,判断是否是回调地址
        parsed_path = urlparse(self.path)
        if parsed_path.path == "/callback":
            # 提取授权码
            query_params = parse_qs(parsed_path.query)
            AUTH_CODE = query_params.get("code", [None])[0]
            
            # 给浏览器返回授权完成提示
            self.send_response(200)
            self.send_header("Content-type", "text/html")
            self.end_headers()
            self.wfile.write(b"<h1>授权完成!请关闭此页面回到脚本。</h1>")
            
            # 关闭HTTP服务器
            self.server.shutdown()
    
    # 屏蔽默认日志输出
    def log_message(self, format, *args):
        return

def run_server():
    server = http.server.HTTPServer(("localhost", PORT), OAuthCallbackHandler)
    server.serve_forever()

if __name__ == "__main__":
    # 启动后台线程运行HTTP服务器
    server_thread = threading.Thread(target=run_server, daemon=True)
    server_thread.start()
    
    # 构造授权URL
    auth_url = f"{AUTHORIZE_URL}?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}"
    
    # 打开浏览器访问授权页面
    webbrowser.open(auth_url)
    
    # 等待授权码获取
    while AUTH_CODE is None:
        pass
    
    # 用授权码换取AccessToken
    token_payload = {
        "grant_type": "authorization_code",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "code": AUTH_CODE,
        "redirect_uri": REDIRECT_URI
    }
    token_response = requests.post(TOKEN_URL, data=token_payload)
    token_data = token_response.json()
    
    # 后续逻辑:使用AccessToken访问API
    print("获取到的AccessToken:", token_data.get("access_token"))

方案二:Flask极简实现(更简洁的代码)

如果不介意安装轻量框架,Flask的写法更直观:

from flask import Flask, request
import threading
import webbrowser
import requests

AUTH_CODE = None
PORT = 8080
REDIRECT_URI = f"http://localhost:{PORT}/callback"

# OAuth配置(替换成你的参数)
CLIENT_ID = "your_client_id"
CLIENT_SECRET = "your_client_secret"
AUTHORIZE_URL = "https://oauth-provider.com/authorize"
TOKEN_URL = "https://oauth-provider.com/token"
SCOPE = "read write"

app = Flask(__name__)

@app.route("/callback")
def callback():
    global AUTH_CODE
    AUTH_CODE = request.args.get("code")
    # 关闭Flask服务器
    shutdown_func = request.environ.get("werkzeug.server.shutdown")
    if shutdown_func:
        shutdown_func()
    return "<h1>授权完成!请关闭此页面回到脚本。</h1>"

if __name__ == "__main__":
    # 启动Flask后台线程
    flask_thread = threading.Thread(target=app.run, kwargs={"port": PORT, "debug": False}, daemon=True)
    flask_thread.start()
    
    # 构造并打开授权URL
    auth_url = f"{AUTHORIZE_URL}?client_id={CLIENT_ID}&redirect_uri={REDIRECT_URI}&response_type=code&scope={SCOPE}"
    webbrowser.open(auth_url)
    
    # 等待授权码
    while AUTH_CODE is None:
        pass
    
    # 换取AccessToken
    token_payload = {
        "grant_type": "authorization_code",
        "client_id": CLIENT_ID,
        "client_secret": CLIENT_SECRET,
        "code": AUTH_CODE,
        "redirect_uri": REDIRECT_URI
    }
    token_response = requests.post(TOKEN_URL, data=token_payload)
    token_data = token_response.json()
    
    print("获取到的AccessToken:", token_data.get("access_token"))

关键注意事项

  • 重定向URI注册:必须在OAuth服务商的后台,把http://localhost:8080/callback(对应你的端口)添加到允许的重定向URI列表中。
  • 端口冲突:如果8080端口被占用,可替换为其他未被使用的端口(比如8000、9000),同时更新重定向URI。
  • 本地测试:无需HTTPS(除非服务商强制要求),用HTTP即可正常运行。

内容的提问来源于stack exchange,提问作者clong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:27:42