nodejs实现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>
  <h1>登录成功跳转首页</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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Selenium399

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值