我的博客開發系列:評論功能之GitHub帳號OAuth受權

前言

​ 由於年前換工做(新工做也沒以前那麼閒了)以及過年的緣由,評論功能的開發進度一直很慢,一點一點的也算是完成了一部分功能,此次先寫第一篇關於GitHub帳號OAuth受權的過程,以後會再寫受權以後如何評論以及評論回覆之類的。javascript

​ 16年寫第一個博客的時候,評論時只須要輸入暱稱以及郵箱便可。此次考慮了下,仍是使用GitHub的帳號來進行訪客用戶的管理比較好,順便練下這類受權登陸(QQ、微信等第三方帳號受權登陸相似)。前端

源碼

前端頁面: Talk is cheap. vue

後端接口: Show me the code.java

GitHub受權過程

1. 在本身的GitHub中註冊OAuth Apps。

OAuth Apps

OAuth Apps

2.點擊觸發登陸,跳轉到受權頁面

點擊受權

// components/Comment.vue 頁面
githubLogin: function () {
      window.location.href = 'https://github.com/login/oauth/authorize?client_id=6625cb27769b1bc52415&redirect_uri=http://localhost:3000/login&scope=user:email';
      window.localStorage.setItem('GITHUB_LOGIN_REDIRECT_URL', `${this.$route.path}?comment=new`);
    }
複製代碼

​ 其中:https://github.com/login/oauth/authorize是須要跳轉的受權地址,client_idredirect_uri都是在GitHub設置中的內容,保持一致便可。scope是獲取用戶信息的範圍,更多的值能夠參考官方文檔ios

localStorage中存儲當前頁面的地址,是爲了後續受權登陸成功以後跳轉到當前的頁面,comment=new參數是爲了與正常訪問的當前頁面做區分。git

4. 跳到官方提供的受權頁面

官方受權頁面

5. 確認受權後會跳轉到http://localhost:3000/login?code=aa043845e6b80253919f頁面

​ 跳轉到login頁面是爲了顯示等待頁面,同事爲了存儲後續接口的返回值,並進行相應的跳轉。最開始是以前跳轉到一個接口的,但處理起來會更麻煩一些。github

// pages/login.vue 頁面
mounted () {
    return axios.get(`/oauth/github/github_oauth?code=${this.$route.query.code}`).then(res => {
      if (res.data.success === 1) {
        let guest = {
          userName: res.data.userName,
          avatar: res.data.avatar
        };
        window.localStorage.setItem('GITHUB_LOGIN_TOKEN', res.data.token);
        window.localStorage.setItem('GITHUB_LOGIN_GUEST', JSON.stringify(guest));
        
        let redirectUrl = window.localStorage.getItem('GITHUB_LOGIN_REDIRECT_URL');
        this.$router.push({ path: redirectUrl });
      }
   	});
}
複製代碼

6. 後端接口根據返回的code值處理受權

​ 此處須要在後端中發起兩個請求:數據庫

​ 1.第一個請求用來獲取到用戶受權後的access_tokenjson

​ 2.第二個請求會根據第一個請求獲取到的access_token來取得用戶信息axios

// server/api/oauth/github.controller.js
exports.githubOAuth = async(ctx) => {
  const code = ctx.query.code;
  let path = 'https://github.com/login/oauth/access_token';
  const params = {
    client_id: config.oAuth.github.client_id,
    client_secret: config.oAuth.github.client_secret,
    code: code
  };
  await fetch(path, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(params)
  })
  .then(res => {
    return res.text();
  })
  .then(body => {
    const args = body.split('&');
    let arg = args[0].split('=');
    return arg[1];
  })
  .then(async(token) => {
    const url = ' https://api.github.com/user?access_token=' + token;
    await fetch(url)
        .then(res => {
          return res.json();
        })
        .then(async(res) => {
          let userId = 0;
          /** * 用戶保存過程,有須要可查看源碼 */
          if (userId > 0) {
            ctx.session.user = res.login;
            // 用戶token
            const userToken = {
              name: res.login,
              id: userId
            };
            // 簽發token
            const token = jwt.sign(userToken, config.tokenSecret, { expiresIn: '2h' });
            ctx.body = {
              success: 1,
              token: token,
			  userName: res.login,
     		  avatar: res.avatar_url,
              message: ''
            };
          } else {
            ctx.body = {
              success: 0,
              token: '',
              message: 'GitHub受權登陸失敗'
            };
          }
        });
  })
  .catch(e => {
    console.log(e);
    ctx.body = {
      success: 0,
      token: '',
      message: 'GitHub受權登陸失敗'
    };
  });
};
複製代碼

總結

​ 通過以上幾個步驟,GitHub的受權流程已經走完,這時咱們的數據庫中也保存下了用戶的一些信息,就能夠繼續進行以後評論的操做了。

相關文章
相關標籤/搜索