github登录不上github第三方登录实现github登录不了




github登录不上github第三方登录实现github登录不了

2022-07-20 21:29:53 网络知识 官方管理员

GitHubOAuth第三方登录

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

导入模块

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><img src="${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>

发表评论:

最近发表
网站分类
标签列表