python +django 實現碼雲(gitee)三方登陸
參考博客:https://v3u.cn/a_id_154
https://www.cnblogs.com/anle123/p/13446182.html
gitee開發文檔:https://gitee.com/api/v5/oauth_doc#/list-item-1
官網地址:https://gitee.com/
OAuth2 認證基本流程
首先注冊碼雲的賬號,並且新建三方應用
a. 點擊自己的頭像進入設置頁面
b.點擊新建三方應用
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
3.填寫應用相關信息,勾選應用所需要的權限。其中: 回調地址是用戶授權后,碼雲回調到應用,並且回傳授權碼的地址
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
應用主頁:要求不嚴格,測試用的話可以直接填http://127.0.0.1:8000/
應用回調地址 :這里要填寫自己定義的視圖路由,我自己的為http://127.0.0.1:8000/gitee_back
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
4.創建成功后,會生成 Cliend ID 和 Client Secret。他們將會在上述OAuth2 認證基本流程用到
vue端代碼
我們這里直接使用window.location.href = url;進行調轉。
這里只寫一個點擊方法
//gitee登陸
gitee:function(){
//創建應用后生成的Cliend ID
var clientId = '*********************************'
//應用回調地址
var redirect_uri = 'http://127.0.0.1:8000/gitee_back'
//拼接要請求的地址
var url = 'https://gitee.com/oauth/authorize?client_id='+clientId+'&redirect_uri='+redirect_uri+'&response_type=code'
// 進行跳轉
window.location.href = url;
},
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
隨后的流程可以參照官方文檔:https://gitee.com/api/v5/oauth_doc#/
django代碼
第一步,通過 瀏覽器 或 Webview 將用戶引導到碼雲三方認證頁面上( GET請求 )
class Gitee(View):
def get(self,request):
return redirect("https://gitee.com/oauth/authorize?client_id=你的應用id&redirect_uri=http://localhost:8000/gitee_back&response_type=code")
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
第二步,如果用戶授權登錄成功,gitee則會通過回調網址將code傳遞給第三方應用,此時三方應用可以通過code換取access_token
class GiteeBack(View):
def get(self,request):
code = request.GET.get("code",None)
r = requests.post("https://gitee.com/oauth/token?grant_type=authorization_code&code=%s&client_id=你的應用id&redirect_uri=http://localhost:8000/gitee_back&client_secret=你的應用秘鑰" % code)
print(r.text)
return HttpResponse("ok")
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
這里我們以基礎用戶信息接口為例子
r = requests.get("https://gitee.com/api/v5/user?access_token=獲取到的accesstoken")
print(r.text)
最后我們會得到一個用戶信息。
\(~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\)
總結:
用戶通過前端點擊gitee登陸圖標,跳轉到gitee授權頁面點擊授權我們會獲取到用戶token,通過token去請求換取用戶身份信息