在Python项目里接入OAuth2.0实现GitHub和微信第三方登录,核心都是走授权码模式。应用先引导用户跳到平台授权页,用户同意后被重定向回我们的回调地址并带上code,后端再用code换token,最后拿token调接口取资料。下面用一张示意图帮助理解整体流程。

一、OAuth2.0授权码模式基本步骤
不管是GitHub还是微信,标准授权码流程都包含四个角色:用户、第三方应用、授权服务器、资源服务器。典型步骤如下:
- 在平台注册应用,拿到client_id和client_secret
- 拼接授权URL,带redirect_uri和scope引导用户跳转
- 用户授权后,平台回调我们的地址并携带code参数
- 后端用code加密钥请求token接口,得到access_token
- 携带token访问用户信息接口,完成登录态写入
二、GitHub第三方登录开发
1. 构造授权链接
GitHub的授权端点为https://github.com/login/oauth/authorize,scope常用user:email。下面用Python生成跳转地址:
import urllib.parse
client_id = "你的github_client_id"
redirect_uri = "https://yourdomain.com/callback/github"
scope = "user:email"
params = {
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": scope,
"state": "random_state_string"
}
auth_url = "https://github.com/login/oauth/authorize?" + urllib.parse.urlencode(params)
print(auth_url)
2. 处理回调并换token
用户在GitHub同意授权后,浏览器访问我们的callback并带code。我们用requests向后端换token:
import requests
code = "从回调query参数拿到"
token_url = "https://github.com/login/oauth/access_token"
resp = requests.post(token_url, headers={"Accept": "application/json"}, data={
"client_id": "你的github_client_id",
"client_secret": "你的github_client_secret",
"code": code,
"redirect_uri": "https://yourdomain.com/callback/github"
})
access_token = resp.json().get("access_token")
3. 拉取GitHub用户信息
user_resp = requests.get("https://api.github.com/user", headers={
"Authorization": f"token {access_token}"
})
user_info = user_resp.json()
print(user_info.get("login"), user_info.get("id"))
三、微信第三方网站登录开发
1. 微信授权链接
微信开放平台网站应用授权地址是https://open.weixin.qq.com/connect/qrconnect,scope填snsapi_login:
import urllib.parse
wx_params = {
"appid": "你的微信appid",
"redirect_uri": "https://yourdomain.com/callback/wechat",
"response_type": "code",
"scope": "snsapi_login",
"state": "random_state"
}
wx_auth_url = "https://open.weixin.qq.com/connect/qrconnect?" + urllib.parse.urlencode(wx_params) + "#wechat_redirect"
print(wx_auth_url)
2. 用code换access_token
微信的token接口返回openid,需要注意它和GitHub字段命名不同:
import requests
wx_code = "回调拿到的code"
wx_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token"
wx_resp = requests.get(wx_token_url, params={
"appid": "你的微信appid",
"secret": "你的微信secret",
"code": wx_code,
"grant_type": "authorization_code"
})
wx_data = wx_resp.json()
access_token = wx_data.get("access_token")
openid = wx_data.get("openid")
3. 获取微信用户信息
wx_user_url = "https://api.weixin.qq.com/sns/userinfo"
wu_resp = requests.get(wx_user_url, params={
"access_token": access_token,
"openid": openid
})
wx_user = wu_resp.json()
print(wx_user.get("nickname"), wx_user.get("unionid"))
四、两者差异与注意点
| 对比项 | GitHub | 微信 |
|---|---|---|
| 授权端点 | github.com/login/oauth/authorize | open.weixin.qq.com/connect/qrconnect |
| token接口 | POST表单 | GET参数 |
| 用户标识 | id | openid/unionid |
开发中要校验state防CSRF,token要安全存储,不要在前端暴露client_secret。使用requests库能大幅简化HTTP交互,遇到微信接口返回乱码可指定resp.encoding。
建议把第三方登录逻辑封装成统一接口,用provider字段区分GitHub与微信,方便后期接入更多平台。