python +django 實現碼雲(gitee)三方登陸
阿新 • • 發佈:2020-12-20
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去請求換取使用者身份資訊