node是怎么實(shí)現(xiàn)github第三方登錄的?下面本篇文章給大家介紹一下nodejs實(shí)現(xiàn)github第三方登錄的方法,希望對(duì)大家有所幫助!
node.js極速入門(mén)課程:進(jìn)入學(xué)習(xí)
一、詳細(xì)流程
二、具體流程
1.注冊(cè)應(yīng)用
①登錄github,Settings=>Developer settings=>OAuth Apps=>Register a new application
②填寫(xiě)應(yīng)用信息
③注冊(cè)完成,得到Client ID和Client Secret
【相關(guān)教程推薦:nodejs視頻教程】
2.前端發(fā)起請(qǐng)求到github授權(quán)頁(yè)面,授權(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>
登錄后復(fù)制
3.后端拿到code,帶著code請(qǐng)求github,拿到token,再將token放在url上傳遞給前端
router.get('/github',controller.auth.githubLogin)
登錄后復(fù)制
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();
登錄后復(fù)制
4.前端創(chuàng)建臨時(shí)頁(yè)面,保存url上的token,并跳轉(zhuǎn)到登錄成功頁(yè)面
臨時(shí)頁(yè)面會(huì)跳轉(zhuǎn)的很快,基本上看不到。
<template> <h1>登錄成功跳轉(zhuǎn)首頁(yè)</h1> </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>
登錄后復(fù)制
三、代碼鏈接
https://github.com/wantao666/nodejs-github