入門|egg.js 入門之egg-jwt

2021-01-13 mySoulCode

小小繼續學習,這次學習的內容是egg-jwt 相關。

創建egg項目

這裡創建一個egg新項目,這裡使用的是ts模式。

npm init egg --type=tsnpm install安裝相關的包

這裡創建並安裝完成以後,需要再次初始化倆包,分別為egg-cors與egg-jwt token 生成的驗證包

npm install egg-cors egg-jwt --save配置相關插件

這裡配置相關的插件

import { EggPlugin } from 'egg';const plugin: EggPlugin = { jwt: { enable: true, package: "egg-jwt" }, cors: { enable: true, package: 'egg-cors', }};export default plugin;配置默認配置文件

config.jwt = { secret: "123456"//自定義 token 的加密條件字符串};config.security = { csrf: { enable: false, ignoreJSON: true }, domainWhiteList: ['http://localhost:8080'],//允許訪問接口的白名單};config.cors = { origin:'*', allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH'};這裡配置完成了相關的默認配置

在根目錄聲明any類型

這裡需要在跟目錄聲明一個any類型,用於前後端發送相關的字符串參數。

import 'egg';declare module 'egg' { interface Application { jwt: any; }}配置相關路由

這裡在app/router.ts 創建相關的路由

import { Application } from 'egg';export default (app: Application) => { const { controller, router, jwt } = app; //正常路由 router.post('/admin/login', controller.admin.login); /* * 這裡的第二個對象不再是控制器,而是 jwt 驗證對象,第三個地方才是控制器 * 只有在需要驗證 token 的路由才需要第二個 是 jwt 否則第二個對象為控制器 **/ router.post('/admin',jwt, controller.admin.index);};這裡就配置完成了相關的路由。

編寫路由對應的控制器

這裡編寫路由所對應的控制器這個控制器在app/controller/home.ts 目錄下

import { Controller } from 'egg';export default class AdminController extends Controller { // 驗證登錄並且生成 token public async login() { const { ctx ,app} = this; //獲取用戶端傳遞過來的參數 const data = ctx.request.body; // 進行驗證 data 數據 登錄是否成功 // ......... //成功過後進行一下操作 //生成 token 的方式 const token = app.jwt.sign({ username: data.username, //需要存儲的 token 數據 //...... }, app.config.jwt.secret); // 生成的token = eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmb28iOiJiYXIiLCJpYXQiOjE1NjAzNDY5MDN9.B95GqH-fdRpyZIE5g_T0l8RgzNyWOyXepkLiynWqrJg // 返回 token 到前端 ctx.body = token; }; //訪問admin數據時進行驗證token,並且解析 token 的數據 public async index() { const { ctx ,app} = this; console.log(ctx.state.user); /* * 列印內容為:{ username : 'admin', iat: 1560346903 } * iat 為過期時間,可以單獨寫中間件驗證,這裡不做細究 * 除了 iat 之後,其餘的為當時存儲的數據 **/ ctx.body = {code:0,msg:'驗證成功'}; }}前端請求相匹配

這裡只需要在前端的authorization欄位裡,添加相關的配置信息即可。

axios({ method: 'post', url: 'http://127.0.0.1:7001/admin', data: { username: 'admin', lastName: '123456' }, headers:{ // 切記 token 不要直接發送,要在前面加上 Bearer 字符串和一個空格 'Authorization':`Bearer ${token}` }}).then(res=>{ console.log(res.data)})這裡就完成了egg.js 結合jwt完成相關的驗證

小tips

這裡插曲一個小tips,這裡使用的是jsonwebtoken。這裡使用jsonwebtoken實現token相關認證機制。

安裝

這裡安裝相關的依賴

npm install jsonwebtoken編寫中間件

在middleware文件下新建一個jwt.ts 文件

'use strict'const fs = require('fs')const path = require('path')const jwt = require('jsonwebtoken') //引入jsonwebtokenmodule.exports = (options, app) => { return async function userInterceptor(ctx, next) { let authToken = ctx.header.authorization // 獲取header裡的authorization if (authToken) { authToken = authToken.substring(7) const res = verifyToken(authToken) // 解密獲取的Token if (res.corpid && res.userid) { // 如果需要限制單端登陸或者使用過程中廢止某個token,或者更改token的權限。也就是說,一旦 JWT 籤發了,在到期之前就會始終有效 // 此處使用redis進行保存 const redis_token = await app.redis.get('loginToken').get(res.corpid + res.userid) // 獲取保存的token if (authToken === redis_token) { ctx.locals.corpid = res.corpid ctx.locals.userid = res.userid await next() } else { ctx.body = { code: 50012, msg: '您的帳號已在其他地方登錄' } } } else { ctx.body = { code: 50012, msg: '登錄狀態已過期' } } } else { ctx.body = { code: 50008, msg: '請登陸後再進行操作' } } }}// 解密,驗證function verifyToken(token) { const cert = fs.readFileSync(path.join(__dirname, '../public/rsa_public_key.pem')) // 公鑰,看後面生成方法 let res = '' try { const result = jwt.verify(token, cert, { algorithms: [ 'RS256' ] }) || {} const { exp } = result, current = Math.floor(Date.now() / 1000) if (current <= exp) res = result.data || {} } catch (e) { console.log(e) } return res}使用中間件

這裡在config.default.js中加入如下的配置,實現中間件的開啟和配置

// 方法一:在應用中使用中間件config.middleware = [ 'jwt' ]config.jwt = { enable: true, ignore: [ '/api/v1/test/', '/public/' ], // 哪些請求不需要認證}// 方法二:router中使用中間件module.exports = app => { const jwt = app.middleware.jwt(); app.router.get('/api/v1/test/', jwt, app.controller.test.test);};token生成

這裡卸載文件裡,用於調用,生成相關的token

loginToken(data, expires = 7200) { const exp = Math.floor(Date.now() / 1000) + expires const cert = fs.readFileSync(path.join(__dirname, '../public/rsa_private_key.pem')) // 私鑰,看後面生成方法 const token = jwt.sign({ data, exp }, cert, { algorithm: 'RS256' }) return token}調用相關的生成方法

const token = ctx.helper.loginToken({ corpid: usersData.corpid, userid: usersData.userid }, 7200) // token生成await app.redis.get('loginToken').set(usersData.corpid + usersData.userid, token, 'ex', 7200) // 保存到redisctx.body = { data: { token, expires: this.config.login_token_time }, code: 1, msg: '登錄成功' } // 返回前端前端使用

這裡前端使用headers,在後面加上相關的空格。

例:axios中// request攔截器service.interceptors.request.use(config => { if (store.getters.token) { config.headers['Authorization'] = `Bearer ${getToken()}` } return config}, error => { console.log(error) Promise.reject(error)})這裡就完成了相關jwt的生成與使用。

小明菜市場

相關焦點

  • egg的意思是雞蛋,你知道a good egg是什麼意思嗎?
    說到egg這個單詞,很容易想到雞蛋這個意思,除了這個意思你還知道其它意思嗎?今天,我們就一起來看一下egg這個單詞。首先,egg可以做名詞,意思是卵、雞蛋等。這句話中的egg意思是卵,是可數名詞。2、Bind the mixture together with a little beaten egg.用少許打過的蛋將混合料攪拌在一起。這句話中的egg意思是雞蛋,通常指用作食物的禽類的蛋。3、The male sperm fertilizes the female egg.雄性的精子使雌性的卵子受精。
  • 漲知識了丨「蛋白」是egg white!「蛋黃」是egg yellow嗎?
    A.egg yellowB.egg innerC.egg yolk可以在評論區回復蛋黃A/蛋黃B/蛋黃C 看看答對了沒~接下來,我們學習一下雞蛋其它部分用英語怎麼說~Eggshell 蛋殼eggshell (noun):the thin, hard, outer layer of an egg
  • egg是雞蛋,apple是蘋果,那「egg apple」是什麼意思呢?猜不到!
    下面我們就具體來看看吧~egg appleegg apple不是雞蛋蘋果,再說也沒有這樣的蘋果啊~所以egg apple是一種形象的比喻說法,意思是指「茄子」。在英語裡,茄子最常見的表達就是eggplant和egg apple,在英式英語裡則是aubergine。
  • EggNOG功能注釋資料庫在線和本地使用
    ;每個eggNOG編號是一類蛋白,將query序列和比對上的eggNOG編號的proteins進行多序列比對,能確定保守位點,分析其進化關係。eggNOG mapper在線版eggNOG-mapper就比對、注釋eggNOG資料庫的專用工具。eggNOG-mapper在線分析,只需滑鼠單擊三步完成。1.訪問在線工具http://eggnogdb.embl.de/#/app/emapper2.參數設置主要是選擇蛋白序列文件,和設置郵箱。一般其它默認即可。
  • leetcode雞蛋掉落問題(egg drop)
    min_times_list = list()             for current_floor in range(1, floor + 1): one_min_times = 1 + max(self.superEggDrop(egg - 1, current_floor - 1), self.superEggDrop(egg, floor
  • or egg first?
    Did the chicken come first or the egg? The chicken comes out of the egg, but the egg is laid by the chicken. So, this goes on for ever, right? Well not exactly.
  • LOL雲頂之弈chinese egg roll陣容是什麼意思 具體出處分享
    首頁 > 部落 > 關鍵詞 > lol最新資訊 > 正文 LOL雲頂之弈chinese egg roll陣容是什麼意思 具體出處分享
  • 「蛋白」是egg white,那「蛋黃」用英語怎麼說呢?
    新東方網>英語>英語學習>語法詞彙>分類詞彙>正文「蛋白」是egg white,那「蛋黃」用英語怎麼說呢?   (Notice how the L is silent in the word yolk 注意在單詞「yolk」中L是不發音的)      Egg white 蛋白   egg white (noun):    the clear liquid of an egg.
  • 萬萬沒想到,lay an egg 還有這個意思!
    就好比」lay an egg」這個短語, 我一直以為就是「下蛋」的意思。直到我某天閱讀時遇到了一個極其簡單的句子」 His joke laid an egg」. 按照字面的理解就是「他的笑話下了個蛋」。噗嗤!自己都不敢相信自己的翻譯。我們都知道 lay an egg的意思是下蛋。
  • 英語學習提升—英語詞彙學習:關於「egg」延伸,你了解多少?
    其實egg除了作為名字外,還可以做動詞,英文釋義是:to throw eggs at somebody or something, especially to express disapproval;to incite somebody to do something, 即朝…扔雞蛋;慫恿某人幹某事;用法是 egg somebody on.
  • 雙語閱讀:a carrot, an egg or a coffee bean?(深度哲理)
    She then asked her to take an egg and break it.「胡蘿蔔,雞蛋和咖啡,」年輕的女人回答。母親把她拉得更近,讓她摸一摸胡蘿蔔。她注意到它們變軟了,然後母親讓她拿一個雞蛋剝開。
  • Egg的幾種英語表達,你確定你知道嘛?
    Over easy↑↑↑The egg just been flipped for a short time.雞蛋只翻面兒煎了一會兒。Over hard↑↑↑The egg has been flipped for a while until the yolk is hard.蛋黃直接翻面兒煎到熟。
  • 「詞彙擴充」雞蛋是egg,那蛋黃、蛋白用英語怎麼說呢?
    雞蛋是我們生活中再熟悉不過的食物了,我們都知道雞蛋的英文是egg, 可如果你想說我只喜歡吃蛋清不喜歡吃蛋黃,是不是很抓耳撓腮.?沒關係,今天就帶大家學習這兩個詞彙。【蛋黃】Egg Yolk(可數名詞)複數形式: egg yolks英英釋義: Egg yolks are the yellow part of an egg.
  • 【腦洞英語】Frozen Egg Technology 凍卵技術
    Please click the blue words "環球時報(英文版)-MySH" to follow the Metro Shanghai of the Global Times."Frozen egg technology is complicated.
  • 「egg」是雞蛋,「plant」是植物,但是「eggplant」是個啥?
    比如,egg是雞蛋,plant是植物,那麼eggplant是個啥?到底是植物還是蛋?誰能想到,eggplant的真身,其實是茄子呢~今天梨子就整理了一些我們中國人常吃的蔬菜的英文,讓你的英語真正地達到實用和接地氣!
  • SpringSecurity + JWT前後端分離架構實現
    JWT交互流程流程圖:認證代碼實現:1.在pom.xml中引入jwt工具包<!3.編寫JwtLoginController類@RestControllerpublic class JwtLoginController {@AutowiredJwtAuthService jwtAuthService;/** * 登錄方法** @param username 用戶名
  • 百達翡麗最不入門的入門款,鸚鵡螺5711和手雷5167
    百達翡麗是世界十大名表之首,也是世界上最為頂級的腕錶品牌,被很多表友當作是終極目標,得到一枚便能人生圓滿。今天王輝表業便來為大家講解一下百達翡麗的入門款——鸚鵡螺和手雷。鸚鵡螺採用了不鏽鋼這種比較親民的材質,而且只有基礎的大三針加上日曆窗的功能,本來應該是降低了百達翡麗的入門門檻,但說它是不入門的入門款,是因為能用公價買到是一件非常幸運的事,事實上其即便有著超高的溢價也是一表難求,或許這就是錶王的能耐。手雷作為鸚鵡螺的衍生之作,其靈感來源於鸚鵡螺,並且其熱度也是隨鸚鵡螺扶搖直上。
  • Node.js 入門 - 使用 Express + Sequelize 實作 API
    課程簡介現代前端開發,無論做什麼都基本離不開 Node.js了。有了 Node.js,js 就成了一個無所不能的語言。無論你是使用 Webpack來打包前端項目,或者來開發Api接口,還是使用 React Native開發原生 App,亦或是開發桌面軟體,Node.js都是必不可少的東西了。Node.js 是一個基於 Chrome V8 引擎的 Javascript 運行環境課程主要講解 如何使用 nvm來安裝 Node.js,以及 npm的用法。