node是怎么實現(xiàn)github第三方登錄的?下面本篇文章給大家介紹一下nodejs實現(xiàn)github第三方登錄的方法,希望對大家有所幫助!
node.js極速入門課程:進入學習
一、詳細流程
二、具體流程
1.注冊應用
①登錄github,Settings=>Developer settings=>OAuth Apps=>Register a new application
②填寫應用信息
③注冊完成,得到Client ID和Client Secret
【相關教程推薦:nodejs視頻教程】
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> <h1>登錄成功跳轉(zhuǎn)首頁</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>
登錄后復制
三、代碼鏈接
https://github.com/wantao666/nodejs-github