溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

node如何實現(xiàn)github第三方登錄

發(fā)布時間:2022-10-27 09:47:11 來源:億速云 閱讀:156 作者:iii 欄目:web開發(fā)

這篇文章主要介紹了node如何實現(xiàn)github第三方登錄的相關(guān)知識,內(nèi)容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇node如何實現(xiàn)github第三方登錄文章都會有所收獲,下面我們一起來看看吧。

一、詳細流程

node如何實現(xiàn)github第三方登錄

二、具體流程

1.注冊應(yīng)用

①登錄github,Settings=>Developer settings=>OAuth Apps=>Register a new application

node如何實現(xiàn)github第三方登錄

node如何實現(xiàn)github第三方登錄
②填寫應(yīng)用信息
node如何實現(xiàn)github第三方登錄

③注冊完成,得到Client IDClient Secret

node如何實現(xiàn)github第三方登錄

2.前端發(fā)起請求到github授權(quán)頁面,授權(quán)成功拿到code重定向到配置的后端callback URL

<a href="https://github.com/login/oauth/authorize?client_id={你自己的cilent_id}&redirect_uri=http://localhost:3001/github" class="iconfont ali-icon-github"></a>

3.后端拿到code,帶著code請求github,拿到token,再將token放在url上傳遞給前端

router.get('/github',controller.auth.githubLogin)
const axios = require('axios')
const querystring = require('querystring')

const config = {
    client_id: "你自己的client_id",
    client_secret: "你自己的client_secret"
}
class AuthController {
    async githubLogin(ctx) {
        const code = ctx.request.query.code
        const params = {
            client_id: config.client_id,
            client_secret: config.client_secret,
            code: code
        }
        let res = await axios.post('https://github.com/login/oauth/access_token', params)
        console.log(res)
        const token = querystring.parse(res.data).access_token
        ctx.cookies.set('token', token, {
            maxAge: ctx.config.jwt.expire * 1000,
        });
        res = { ...ctx.errCode.SUCCESS, data: { token } };
        ctx.redirect('http://172.25.78.33:8081/login/success?token='+token)
    }
}
module.exports = exports = new AuthController();

4.前端創(chuàng)建臨時頁面,保存url上的token,并跳轉(zhuǎn)到登錄成功頁面

臨時頁面會跳轉(zhuǎn)的很快,基本上看不到。

<template>
  <h2>登錄成功跳轉(zhuǎn)首頁</h2>
</template>

<script>
import {setLoginedUser} from "@/http/axios";
export default {
  mounted() {
    setLoginedUser("github", this.$route.query.token);
    this.$message({
      message: "登錄成功",
      type: "success",
    });
    this.$router.push("/home");
  },
};
</script>

<style>
</style>

關(guān)于“node如何實現(xiàn)github第三方登錄”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“node如何實現(xiàn)github第三方登錄”知識都有一定的了解,大家如果還想學習更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI