欢迎光临
我们一直在努力

node如何实现github第三方登录

这篇文章主要介绍了node如何实现github第三方登录的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇node如何实现github第三方登录文章都会有所收获,下面我们一起来看看吧。

一、详细流程

二、具体流程

1.注册应用

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

②填写应用信息

③注册完成,得到Client IDClient Secret

2.前端发起请求到github授权页面,授权成功拿到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.前端创建临时页面,保存url上的token,并跳转到登录成功页面

临时页面会跳转的很快,基本上看不到。

<template>
  <h2>登录成功跳转首页</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>

关于“node如何实现github第三方登录”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“node如何实现github第三方登录”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注云搜网行业资讯频道。

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。