Node.js和vue3实现GitHub OAuth第三方登录

2024-09-08 03:20

本文主要是介绍Node.js和vue3实现GitHub OAuth第三方登录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Node.js和vue3实现GitHub OAuth第三方登录

前言

第三方登入太常见了,微信,微博,QQ…总有一个你用过。

在开发中,我们希望用户可以通过GitHub账号登录我们的网站,这样用户就不需要注册账号,直接通过GitHub账号登录即可。

效果演示

在这里插入图片描述

注册配置 GitHub 应用

1.首先登录你的GitHub然后点击右上角的头像->点击进入Settings页面

在这里插入图片描述

2.在Settings页面中点击左侧边栏的 Developer settings

在这里插入图片描述

3.然后点击OAuth Apps,点击 Register a new application

一个用户或组织最多可以拥有100个OAuth应用。

在这里插入图片描述

4.填写应用信息

我这边使用了腾讯翻译插件,为了照顾英语不好的朋友观看理解。

在这里插入图片描述

这里主要是Authorization callback URL的填写;

这个应用回调地址就是上面登录流程授权之后返回的redirect_uri

5.点击Generate new client secret生成Client Secret

在这里插入图片描述

6.将Client IDClient Secret复制到配置文件,用于后面向GitHub发送请求传参。

注意: 只会出现一次Client secrets,自己保存好

在这里插入图片描述

前后端调用流程步骤:

  • 前端:用户点击按钮跳转到GitHub授权页面;
  • 前端:用户在授权页面同意授权后,GitHub将用户重定向到您的网站;
  • 前端:重定向的URL中包含一个授权码code,在该页面中获取授权码;
  • 前端:调用后端登录api,将获取到的code传给后端;
  • 后端:后端收到code后调用GitHub的token api,获取access_token;
  • 后端:获取到access_token后调用 user api,获取用户信息返回给前端;
  • 前端:拿到后端返回的用户信息后,将用户信息保存到本地,完成登录。

前端 Vue 实现

1.安装必要依赖

  • axios是一个HTTP客户端库,用于向服务端发送请求。
npm install axios

2.替换你的配置信息

// github配置信息
const config = {// 替换为你的回调地址redirect_uri: 'http://127.0.0.1:9090/pages/login/login',// 替换为你的 client_idclient_id: 'Ov23li3ZcThmL87YHUBL',
}

3.代码示例

<template><div class="user-box"><div v-if="userInfo.id" class="user-info"><img class="user-img" :src="userInfo.avatar_url" /><text class="user-name">用户昵称:{{ userInfo.name || userInfo.login }}</text><text class="user-openid">nodeId{{ userInfo.node_id }}</text></div><div v-else class="user-empty">{{ loading ? '用户登录中...' : userInfo?.id ? '用户已登录' : '用户未登录' }}</div></div><button @click="oauth">发起GitHub授权</button>
</template><script setup>
import { onMounted, ref } from 'vue'
import axios from 'axios'
const loading = ref(false)
let userInfo = ref({})
// github配置信息
const config = {// 替换为你的回调地址redirect_uri: 'http://127.0.0.1:9090/pages/login/login',// 替换为你的 client_idclient_id: 'Ov23li3ZcThmL87YHUBL',
}// 请求后端登录
function reqLogin(code) {console.log('3.将获取到的code发送给后端进行登录');if (loading.value) returnloading.value = trueaxios.post('http://127.0.0.1:3000/api/github/login', { code }).then(res => {// 前端拿到用户信息后,可以保存到数据库或者本地,或者直接跳转到个人中心页面。console.log('4.登录成功获取到用户信息', res.data);userInfo.value = res.data}).catch(err => {console.log('登录出错了!', err);}).finally(() => {console.log('finally');loading.value = false})
}// 获取地址栏中的code 获取不到将返回 null
function getCode() {// 获取当前 URL 的查询参数const urlParams = new URLSearchParams(window.location.search);// 从查询参数中获取 'code' 值const code = urlParams.get('code');if (code) {console.log('2.授权后,获取地址栏中的code');}return code
}// 发起授权
function oauth() {console.log('1.点击授权按钮,跳转到GitHub授权页中');const url = `https://github.com/login/oauth/authorize?client_id=${config.client_id}&redirect_uri=${config.redirect_uri}`window.location.href = url
}onMounted(() => {const code = getCode()if (code) reqLogin(code)
})
</script><style scoped lang="scss">
.user-box {display: flex;align-items: center;justify-content: center;margin-bottom: 20px;.user-info {display: flex;flex-direction: column;align-items: center;justify-content: center;.user-img {width: 60px;height: 60px;border-radius: 99px;border: 1px solid black;}}.user-empty {// background-color: #f5f6f7;display: flex;align-items: center;justify-content: center;width: 100px;height: 100px;border: 1px solid black;border-radius: 6px;}
}
</style>

后端 Node.js 实现

1.安装必要依赖

  • express是一个Web应用框架,用于构建Web应用。
  • cors是一个中间件,用于处理跨域请求。
  • axios是一个HTTP客户端库,用于向服务端发送请求。
npm install express cors axios 

2.替换你的配置信息

// github配置信息
const githubConfig = {// 替换为你的回调地址redirect_uri: 'http://127.0.0.1:9090/pages/login/login',// 替换为你的 client_idclient_id: 'Ov23li3ZcThmL87YHUBL',// 替换为你的 client_secretclient_secret: 'e021cb59a650476e62be3ee72fc9686e2c86c1d3',
}

3.代码示例

// Node.js和vue3实现GitHub OAuth第三方登录
const express = require('express'); // 导入 Express 模块
const cors = require('cors'); // 导入 CORS 模块,用于处理跨域请求
const axios = require('axios'); // 导入 Axios 模块,用于发起 HTTP 请求const app = express(); // 创建 Express 应用实例
app.use(cors()); // 使用 CORS 中间件解决跨越请求
app.use(express.json()) // 解析 json 格式请求体
app.use(express.urlencoded({ extended: true })) // 解析传统表单请求体// github配置信息
const githubConfig = {// 替换为你的回调地址redirect_uri: 'http://127.0.0.1:9090/pages/login/login',// 替换为你的 client_idclient_id: 'Ov23li3ZcThmL87YHUBL',// 替换为你的 client_secretclient_secret: 'e021cb59a650476e62be3ee72fc9686e2c86c1d3',
}// github登录
app.post('/api/github/login', async (req, res) => {// 1、校验必填参数if (!req.body.code) {throw new Error('必填参数不能为空!')}// 2、获取 Access tokenconst accessTokenInfo = await getAccessToken(req.body.code)// 3、获取用户信息const userInfo = await getUserInfo(accessTokenInfo.access_token)// 4、在这步你可以将用户信息存入数据库中等其他操作,这里我直接返回了res.status(200).send(userInfo)
})// 获取 access_token
async function getAccessToken(code) {//官方文档: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps// 1、验证后端传来的codeif (!code || code.length !== 20) {throw new Error('code参数不正确!');}// 2、向github发送post请求,成功的话会,response.data里面有一个access_tokenconst response = await axios({method: 'post',url: 'https://github.com/login/oauth/access_token',params: {redirect_uri: githubConfig.redirect_uri,client_id: githubConfig.client_id,client_secret: githubConfig.client_secret,code,},headers: { 'accept': 'application/json' },});if (!response.data?.access_token) {throw new Error('获取 access_token 失败!' + JSON.stringify(response.data))}// response.data:{//   "access_token":"gho_16C7e42F292c6912E7710c838347Ae178B4a",//   "scope":"repo,gist",//   "token_type":"bearer"// }return response.data
}// 获取用户信息
async function getUserInfo(access_token) {//官方文档: https://docs.github.com/en/apps/oauth-apps/building-oauth-apps/authorizing-oauth-apps#3-use-the-access-token-to-access-the-apiconst response = await axios({method: "get",url: 'https://api.github.com/user',headers: {Authorization: `Bearer ${access_token}`,},});if (!response.data?.id) throw new Error('获取用户信息失败!')/**response.data = {"login": "China-quanda","id": 36378336,"node_id": "MDQ6VXNlcjM2Mzc4MzM2","avatar_url": "https://avatars.githubusercontent.com/u/36378336?v=4","gravatar_id": "","url": "https://api.github.com/users/China-quanda","html_url": "https://github.com/China-quanda","followers_url": "https://api.github.com/users/China-quanda/followers","following_url": "https://api.github.com/users/China-quanda/following{/other_user}","gists_url": "https://api.github.com/users/China-quanda/gists{/gist_id}","starred_url": "https://api.github.com/users/China-quanda/starred{/owner}{/repo}","subscriptions_url": "https://api.github.com/users/China-quanda/subscriptions","organizations_url": "https://api.github.com/users/China-quanda/orgs","repos_url": "https://api.github.com/users/China-quanda/repos","events_url": "https://api.github.com/users/China-quanda/events{/privacy}","received_events_url": "https://api.github.com/users/China-quanda/received_events","type": "User","site_admin": false,"name": "Quanda","company": null,"blog": "","location": "北京","email": null,"hireable": null,"bio": null,"twitter_username": null,"notification_email": null,"public_repos": 6,"public_gists": 0,"followers": 0,"following": 2,"created_at": "2018-02-11T17:35:16Z","updated_at": "2024-09-07T10:31:22Z"}*/return response.data;
}// 启动服务
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {console.log(`Server running on http://127.0.0.1:${PORT}`);
});

总结

  1. 首先,在github上注册一个应用,并配置好回调地址,获取client_idclient_secret
  2. 在前端页面上,通过点击发起GitHub授权按钮,替换当前地址为 https://github.com/login/oauth/authorize,携带上我们前面获取的client_id和回调地址。
  3. github会返回一个code,这个code是临时的,我们通过这个code向github请求access_token,再通过access_token向github请求用户信息。
  4. 最后,将用户信息返回给前端,前端拿到用户信息后,可以保存到数据库或者本地,或者直接跳转到个人中心页面。
  5. 注意,这个项目只是演示如何实现github登录,实际应用中,需要做更多的处理,比如用户注册,用户信息保存等。
  6. 示例代码仅供参考,实际应用中,需要根据具体的业务需求进行修改。
  7. 示例代码中,没有做任何的错误处理,实际应用中,需要做错误处理。

我们发现第三方登录的流程其实都差不多,差别就是不同的平台,和自己应用的业务会有点不一样。所以呢,在做之前先要理清思路,仔细看文档。

这篇关于Node.js和vue3实现GitHub OAuth第三方登录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/1146966

相关文章

Spring Boot 实现 IP 限流的原理、实践与利弊解析

《SpringBoot实现IP限流的原理、实践与利弊解析》在SpringBoot中实现IP限流是一种简单而有效的方式来保障系统的稳定性和可用性,本文给大家介绍SpringBoot实现IP限... 目录一、引言二、IP 限流原理2.1 令牌桶算法2.2 漏桶算法三、使用场景3.1 防止恶意攻击3.2 控制资源

springboot下载接口限速功能实现

《springboot下载接口限速功能实现》通过Redis统计并发数动态调整每个用户带宽,核心逻辑为每秒读取并发送限定数据量,防止单用户占用过多资源,确保整体下载均衡且高效,本文给大家介绍spring... 目录 一、整体目标 二、涉及的主要类/方法✅ 三、核心流程图解(简化) 四、关键代码详解1️⃣ 设置

Nginx 配置跨域的实现及常见问题解决

《Nginx配置跨域的实现及常见问题解决》本文主要介绍了Nginx配置跨域的实现及常见问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来... 目录1. 跨域1.1 同源策略1.2 跨域资源共享(CORS)2. Nginx 配置跨域的场景2.1

Python中提取文件名扩展名的多种方法实现

《Python中提取文件名扩展名的多种方法实现》在Python编程中,经常会遇到需要从文件名中提取扩展名的场景,Python提供了多种方法来实现这一功能,不同方法适用于不同的场景和需求,包括os.pa... 目录技术背景实现步骤方法一:使用os.path.splitext方法二:使用pathlib模块方法三

CSS place-items: center解析与用法详解

《CSSplace-items:center解析与用法详解》place-items:center;是一个强大的CSS简写属性,用于同时控制网格(Grid)和弹性盒(Flexbox)... place-items: center; 是一个强大的 css 简写属性,用于同时控制 网格(Grid) 和 弹性盒(F

CSS实现元素撑满剩余空间的五种方法

《CSS实现元素撑满剩余空间的五种方法》在日常开发中,我们经常需要让某个元素占据容器的剩余空间,本文将介绍5种不同的方法来实现这个需求,并分析各种方法的优缺点,感兴趣的朋友一起看看吧... css实现元素撑满剩余空间的5种方法 在日常开发中,我们经常需要让某个元素占据容器的剩余空间。这是一个常见的布局需求

CSS Anchor Positioning重新定义锚点定位的时代来临(最新推荐)

《CSSAnchorPositioning重新定义锚点定位的时代来临(最新推荐)》CSSAnchorPositioning是一项仍在草案中的新特性,由Chrome125开始提供原生支持需... 目录 css Anchor Positioning:重新定义「锚定定位」的时代来了! 什么是 Anchor Pos

CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比

《CSS中的Static、Relative、Absolute、Fixed、Sticky的应用与详细对比》CSS中的position属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布... css 中的 position 属性用于控制元素的定位方式,不同的定位方式会影响元素在页面中的布局和层叠关

HTML5 getUserMedia API网页录音实现指南示例小结

《HTML5getUserMediaAPI网页录音实现指南示例小结》本教程将指导你如何利用这一API,结合WebAudioAPI,实现网页录音功能,从获取音频流到处理和保存录音,整个过程将逐步... 目录1. html5 getUserMedia API简介1.1 API概念与历史1.2 功能与优势1.3

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja