准备
登录github 选择右上角的setting Developer settings -> OAuth Apps -> Register a new application 填入基本信息 点击绿色的按钮,可以看见 client_id 和 client secret
理清思路:
开始时,一个登录的连接,点击连接.后台监听登录(/login
)路由,然后重定向到github授权的路由(此时需要带上上面生成的Client ID) 当重定向(302)到授权的路由时,如果Client ID正确,会返回在准备阶段填写的Authorization callback URL
.以及一个code 本地后台监听 /github/callback
, 获取code后,生成参数,重新访问 github的 https://github.com/login/oauth/access_token
, 以获取token 如果 Client ID 和 Client Secret 正确, 访问github授权url时,会得到一个token 获得token即验证成功.
代码实现:
< html> < head> < script src = " https://cdn.jsdelivr.net/npm/vue/dist/vue.js" > </ script> < script src = " https://unpkg.com/axios/dist/axios.min.js" > </ script> </ head> < body> < div id = " app" > < a href = " http://localhost:3000/github/login" > login with github</ a> </ div> </ body>
</ html>
const koa = require ( "koa" ) ;
const router = require ( 'koa-router' ) ( ) ;
const static = require ( 'koa-static' ) ;
const app = new koa ( ) ;
const axios = require ( "axios" ) ;
const querystring = require ( "querystring" ) ; app. use ( static ( __dirname + '/' ) ) ;
const config = { client_id: '9ffe8aeafb6a5b1469b9' , client_secret: 'd25a747d52f74e98303f1bff0a8714fc8488c221'
} router. get ( '/github/login' , async ( ctx) => { var dataStr = ( new Date ( ) ) . valueOf ( ) ; var path = "https://github.com/login/oauth/authorize" ; path += '?client_id=' + config. client_id; ctx. redirect ( path) ;
} )
router. get ( '/github/callback' , async ( ctx) => { const code = ctx. query. code; const params = { client_id: config. client_id, client_secret: config. client_secret, code: code} let res = await axios. post ( 'https://github.com/login/oauth/access_token' , params) ; const access_token = querystring. parse ( res. data) . access_token; res = await axios. get ( 'https://api.github.com/user?access_token=' + access_token) ; ctx. body = `<h1>Hello ${ res. data. login} </h1><img src=' ${ res. data. avatar_url} alt=""' />`
} ) app. use ( router. routes ( ) ) ;
app. use ( router. allowedMethods ( ) ) ;
app. listen ( 3000 ) ;
操作:
vscode下打开html的快捷键, alt + b 点击链接 输入账号密码登录 成功!