首页 >web前端 >js教程 >浅析node是怎么实现github第三方登录的

浅析node是怎么实现github第三方登录的

青灯夜游
青灯夜游转载
2022-10-26 19:23:171927浏览

node是怎么实现github第三方登录的?下面本篇文章给大家介绍一下nodejs实现github第三方登录的方法,希望对大家有所帮助!

在这里插入图片描述

一、详细流程

在这里插入图片描述

二、具体流程

1.注册应用

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

在这里插入图片描述

在这里插入图片描述
②填写应用信息
在这里插入图片描述

③注册完成,得到Client IDClient Secret

在这里插入图片描述

【相关教程推荐:nodejs视频教程

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(&#39;/github&#39;,controller.auth.githubLogin)
const axios = require(&#39;axios&#39;)
const querystring = require(&#39;querystring&#39;)

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(&#39;https://github.com/login/oauth/access_token&#39;, params)
        console.log(res)
        const token = querystring.parse(res.data).access_token
        ctx.cookies.set(&#39;token&#39;, token, {
            maxAge: ctx.config.jwt.expire * 1000,
        });
        res = { ...ctx.errCode.SUCCESS, data: { token } };
        ctx.redirect(&#39;http://172.25.78.33:8081/login/success?token=&#39;+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

更多node相关知识,请访问:nodejs 教程

以上是浅析node是怎么实现github第三方登录的的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:csdn.net。如有侵权,请联系admin@php.cn删除