生活随笔 
收集整理的這篇文章主要介紹了
                                
koa ---  使用Github OAuth登录 
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
 
                                
                            準備  
登錄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> < scriptsrc = " https://cdn.jsdelivr.net/npm/vue/dist/vue.js" > </ script> < scriptsrc = " https://unpkg.com/axios/dist/axios.min.js" > </ script> </ head> < body> < divid = " app" > < ahref = " 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 點擊鏈接 輸入賬號密碼登錄 成功! 
                            總結 
                            
                                以上是生活随笔 為你收集整理的koa ---  使用Github OAuth登录 的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                            
                                如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。