GitHub OAuth 第三方登录
导入模块
const Koa = require("koa"); const router = require("koa-router")(); const static = require("koa-static"); const axios = require("axios"); const querystring = require("querystring");
初始化 App
const app = new Koa(); app.use(static(__dirname + "/")); // TODO 路由待补充 app.use(router.routes()); app.listen(7001);
登录 GitHub 申请 AuthApp:
Settings/Developer/settings/AuthApp
const config = { client_id: "", client_secret: "", };
第一步:前端触发服务器接口由服务器重定向到 Github 授权页面
router.get("/github/login", async (ctx) => { const path = `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); const params = { client_id: config.client_id, client_secret: config.client_secret, code: code, }; let ret = await axios.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); const params = { client_id: config.client_id, client_secret: config.client_secret, code: code, }; let ret = await axios.post( "https://github.com/login/oauth/access_token", params ); const { access_token } = querystring.parse(ret.data); console.log("access_token: ", access_token); ret = await axios.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 部分:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Login with github</title> </head> <body> <a href="/github/login">Login with github</a> </body> </html>