日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

koa --- 使用Github OAuth登录

發布時間:2023/12/10 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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即驗證成功.
  • 代碼實現:

    • index.html
    <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>
    • index.js
    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登录的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。