1. 程式人生 > 程式設計 >vue實現GitHub的第三方授權方法示例

vue實現GitHub的第三方授權方法示例

目錄
  • 建立OAuth Apps
  • 獲取code
  • 獲取access_token
  • 獲取使用者資訊

最近在完善我的部落格系統,突然想到從原本臨時填寫 name + email 進行評論改成使用授權登陸以發表評論。
廢話不多說,直接奔入主題

溫馨提示:本文章只滿足個人使用需求,如果需要學習更詳細的使用方法,可訪問 OAuth官方文件。

建立OAuth Apps

首先,你需要一個GitHub賬戶然後前往GitHub developers,根據要求填寫完成之後,會自動生成Client_ID和Client Secret,在之後的步驟中會用到。

獲取code

//method
async githubLogin() {
 windows.location.href = 
    "https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_ur
iwww.cppcns.com=your_redirect_uri" }
<a href="https://github.com/login/oauth/authorize?client_id = your_client_id&redirect_uri=your_redirect_uri">GitHub登陸</a>

路由引數中redirect_uri是可選的。如果省略,則GitHub將重定向到你在OAuth apps配置的回撥路徑。如果提供,則你所填寫的redirect_uri必須是你在OAuth apps中配置的回撥路徑的子路徑。如下:

CALLBACK: http://xx.com/github

GOOD: http://xx.com/github
GOOD: http://xx.com/github/path/path
BAD: http://xx.com/git
BAD: http://xxxxx.com/path

如果用戶接受你的請求,將會跳轉CdHfCkN到redirect_uri,我們可以接受路由中的引數code,以進行下一步操作。

your_redirect_uhttp://www.cppcns.comri?code=xxx

獲取access_token

我們需要client_id、client_secret和code來獲取access_token。

/*
/githubAccessToken:https://github.com/login/oauth/access_token
*/
this.$axios
 .get('/githubAccessToken',{
 params: {
  client_id: your_client_id,client_secret: your_client_secret,code: your_code
  }
 })

預設情況下,你會獲取如下響應:

access_token=xxxxx&token_type=bearer

如果你想用更方便的格式接收響應,你可以在headers中自定義Accept:

Accept: "application/on"
=> {"access_token":xxxxx,"token_type":bearer}

獲取使用者資訊

獲取access_token之後,我們就可以請求使用者的部分資訊了:

/*
/githubUserInfo:https://api.github.com/user
*/
this.$axios
 .get('/githubUserInfo',{
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",Accept: "application/json",Authorization: `token ${access_token}` //必填
  }
})

然後你便可以獲取到使用者資訊了。

到此這篇關於實現GitHub的第三方授權的文章就介紹到這了,更多相關vue實現GitHub的第三方授權內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!