无缝集成:一键登录码云和GitHub,提升用户体验与应用安全

用户认证和登录系统是几乎所有应用程序的关键部分。为了简化用户体验并提供更多的登录选项,许多应用程序选择集成第三方登录,如码云(Gitee)和GitHub。这种集成使用户能够使用他们已经拥有的社交媒体或开发者平台帐户登录您的应用程序,无需创建新的用户名和密码。

废话少说,跟着我一步一步来

实现WEB端码云和github登录

体验地址:admin.zhouyi.run

不论是gitee还是github差不多都是这样的原理:

Gitee OAuth方案

  1. 创建要接入码云的应用(gitee.com/oauth/appli...)。
  • 如果回调地址还没有写 可以随便先填一个接口地址

创建成功后,会生成 Cliend ID 和 Client Secret。他们将会在获取授权码和access_token的步骤中使用到

  1. 前端实现 (vue3)
js 复制代码
// 码云登录方法 携带刚刚创建的应用中的client_id 跳转至码云authorize页面
const giteeLogin = () => {
  let client_id = 'b1297****fe5'
  // 这个回调地址在后面再说
  let redirect_uri = 'http://localhost/:3089/v1/sys/auth/giteeLogin'
  window.open(`https://gitee.com/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=code`, '_blank')
}
  1. 后端接口实现(express.js) 上面提到的有个回调地址是用来接收授权码、获取access_token和用户信息三个步骤
js 复制代码
// 实现回调接口:http://localhost:3089/v1/sys/auth/giteeLogin
exports.giteeLogin = [
    // 参数验证
    [query("code").notEmpty().withMessage('码云授权码不能为空.')],
    async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                // 处理验证错误并返回适当的响应
                return apiResponse.validationErrorWithData(res, errors.array()[0].msg);
            } else {
                // 码云 OAuth 应用的客户端ID、客户端秘钥和回调URL
                const CLIENT_ID = 'b12*******5';
                const CLIENT_SECRET = 'd****89';
                const REDIRECT_URI = 'http://localhost:3089/v1/sys/auth/giteeLogin';

                // 从请求中获取授权码
                const code = req.query.code;

                // 使用授权码获取访问令牌
                const tokenResponse = await axios.post('https://gitee.com/oauth/token', querystring.stringify({
                    code,
                    client_id: CLIENT_ID,
                    client_secret: CLIENT_SECRET,
                    redirect_uri: REDIRECT_URI,
                    grant_type: 'authorization_code',
                }));

                const accessToken = tokenResponse.data.access_token;

                // 使用访问令牌访问码云API获取用户信息
                const userResponse = await axios.get('https://gitee.com/api/v5/user', {
                    headers: {
                        Authorization: `Bearer ${accessToken}`,
                    },
                });

                const user = userResponse.data;

                // 重定向到前端登录页面并传递用户数据
                return res.redirect('http://localhost:3088/#/login?userData=' + JSON.stringify(user));
                    
        } catch (err) {
            log.error(`*** 码云授权登录失败请重新登录 ** 错误信息 : ${JSON.stringify(err)}`);
            return apiResponse.ErrorResponse(res, err);
        }
    }
];

完~

Github OAuth方案

  1. 创建要接入Github的应用(github.com/settings/ap...)。

创建成功后,会生成 Cliend ID 和 Client Secret。他们将会在获取授权码和access_token的步骤中使用到

  1. 前端实现 (vue3)
js 复制代码
const githubLogin = () => {
  let client_id = 'e*******'
  let redirect_uri = 'http://localhost:3089/v1/sys/auth/githubLogin'
  window.open(`https://github.com/login/oauth/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}`, '_blank')
}
  1. 后端接口实现 (express.js) 上面提到的有个回调地址是用来接收授权码、获取access_token和用户信息三个步骤
js 复制代码
// 实现回调地址:http://localhost:3089/v1/sys/auth/githubLogin
exports.githubLogin = [
    // 参数验证
    [
        query("code").notEmpty().withMessage('github授权码不能为空.'),
    ],
    async (req, res) => {
        try {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                // 处理验证错误并返回适当的响应
                return apiResponse.validationErrorWithData(res, errors.array()[0].msg);
            } else {
                // github OAuth 应用的客户端ID、客户端秘钥和回调URL 
                const CLIENT_ID = '****';
                const CLIENT_SECRET = '*****f9017cd9b043';
                const REDIRECT_URI = 'http://localhost:3089/v1/sys/auth/githubLogin';

                // 从请求中获取授权码
                const code = req.query.code;

                // 使用授权码获取访问令牌
                const tokenResponse = await axios.post('https://github.com/login/oauth/access_token', {
                        code,
                        client_id: CLIENT_ID,
                        client_secret: CLIENT_SECRET,
                        redirect_uri: REDIRECT_URI,
                    },
                    {
                        headers: {
                            'Accept': 'application/json',
                        },
                    });

                const accessToken = tokenResponse.data.access_token;

                // 使用访问令牌访问码云API获取用户信息
                const userResponse = await axios.get('https://api.github.com/user', {
                    headers: {
                        'Accept': 'application/json',
                        Authorization: `Bearer ${accessToken}`,
                    },
                });
                const user = userResponse.data;

             // 重定向到前端登录页面并传递用户数据
              return res.redirect('http//localhost:3088/#/login?userData=' + JSON.stringify(user ));
            }
        } catch (err) {
            log.error(`*** github授权登录失败请重新登录 ** 错误信息 : ${JSON.stringify(err)}`);
            return apiResponse.ErrorResponse(res, err);
        }
    }
];

完~

体验地址:admin.zhouyi.run

最后

集成码云和GitHub登录功能是为应用程序提供更广泛的用户访问渠道的有效方式。可以直接使用文中的前端和后端示例代码

相关推荐
天若有情6731 小时前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
FYKJ_20102 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
历程里程碑3 小时前
4 Git远程协作:从零开始,玩转仓库关联与代码同步(带实操代码讲解)
大数据·c++·git·elasticsearch·搜索引擎·gitee·github
天若有情6734 小时前
自己开发一款极简 Vanilla 原生前端框架,已开源上架 NPM & GitHub
前端框架·npm·github
fthux5 小时前
用了 GitZip 这么多年,我动手做了一个「Pro」版
人工智能·开源·github
用户6688599847667 小时前
Vue 3.0安装与使用
vue.js
空中海7 小时前
01 React Native 基础、核心组件与布局体系
javascript·react native·react.js
yuanyuan2o28 小时前
Git merge 的几种不同模式
git·github
前端之虎陈随易9 小时前
2年没用Nodejs了,Bun很香
linux·前端·javascript·vue.js·typescript