1. 主页 > 用户投稿

github登录不上(github第三方登录实现)

GitHub OAuth 第三方登录

导入模块

constKoa=require("koa");constrouter=require("koa-router")();conststatic=require("koa-static");constaxios=require("axios");constquerystring=require("querystring");

初始化 App

constapp=newKoa();app.use(static(__dirname+"/"));//TODO路由待补充app.use(router.routes());app.listen(7001);

登录 GitHub 申请 AuthApp:

Settings/Developer/settings/AuthApp

constconfig={client_id:"",client_secret:"",};

第一步:前端触发服务器接口由服务器重定向到 Github 授权页面

router.get("/github/login",async(ctx)=>{constpath=`https://github.com/login/oauth/authorize?client_id=${config.client_id}`;ctx.redirect(path);});

第二步:GitHub 验证授权信息后重定向到服务器接口返回 Code

router.get("/auth/github/callback",async(ctx)=>{const{code}=ctx.query;console.log("code:",code);//TODO其他部分待实现});

第三步:服务器通过 code 换取 accesstoken

router.get("/auth/github/callback",async(ctx)=>{const{code}=ctx.query;console.log("code:",code);constparams={client_id:config.client_id,client_secret:config.client_secret,code:code,};letret=awaitaxios.post("https://github.com/login/oauth/access_token",params);const{access_token}=querystring.parse(ret.data);console.log("access_token:",access_token);//TODO其他部分待实现});

第四步:使用 accesstoken 获取用户信息,服务器做登录态处理

router.get("/auth/github/callback",async(ctx)=>{const{code}=ctx.query;console.log("code:",code);constparams={client_id:config.client_id,client_secret:config.client_secret,code:code,};letret=awaitaxios.post("https://github.com/login/oauth/access_token",params);const{access_token}=querystring.parse(ret.data);console.log("access_token:",access_token);ret=awaitaxios.get(`https://api.github.com/user`,{headers:{Authorization:`token${access_token}`},});console.log("user:",ret.data);ctx.body=`<h1>Hello${ret.data.login}</h1><imgsrc="${ret.data.avatar_url}">`;});

补充 Html 部分:

<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"/><metahttp-equiv="X-UA-Compatible"content="IE=edge"/><metaname="viewport"content="width=device-width,initial-scale=1.0"/><title>Loginwithgithub</title></head><body><ahref="/github/login">Loginwithgithub</a></body></html>

以上就是爱惜日网»github登录不上(github第三方登录实现)的相关内容了,更多精彩请关注作者:爱惜日号SEO专员

声明:本文由爱惜日网/爱惜日号作者编辑发布,更多技术关注!

本文内容由互联网用户自发贡献,该文观点仅代表作者本人。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 203304862@qq.com

本文链接:https://jinnalai.com/n/31711.html

联系我们

在线咨询:点击这里给我发消息

微信号:

工作日:9:30-18:30,节假日休息