egg-jwt 是一個生成token的插件
token的規則:
服務器返回的token數據基本結構是 Header.Payload.Signature, header、payload、signature三部分以'.'隔開。
例如:
1
2
3
|
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VyTmFtZSI6ImNlc2hpemhhbmdodTAyIiwiaWF0IjoxNTU1MjEyMzg1LCJleHAiOjE1NTUyMTU5ODV9.
K53kd6cERhp6H4mtd8jCzA2bQtJTsdA2Kh3hzbXMXbU
|
header: 一個json對象,描述JWT的元數據
payload: 一個 JSON 對象,用來存放實際需要傳遞的數據
signature: 對header和payload兩部分的簽名,防止數據被篡改
安裝:
npm i egg-jwt --save // 或 yarn add egg-jwt
導入到egg項目里:
// 在config/plugin.js里面添加 exports.jwt = { enable: true, package: 'egg-jwt', }, // 或者,在config/plugin.js的module.exports里面添加 jwt: { enable: true, package: 'egg-jwt', },
配置:
// 在config/config.default.js的module.exports里面添加 config.jwt = { secret: '123456', };
通過 jwt 生成 token:
app/controller/user.js
// 登錄 async login() { const { ctx, app } = this; // post請求傳來的參數 const { name } = ctx.request.body; // 判斷數據庫里面是否存在該用戶 const user = await ctx.service.user.login(name); if(user){ // 用戶存在,生成token const token = app.jwt.sign({ name: user.name, }, app.config.jwt.secret); ctx.body = { code: 200, message: '登錄成功', data: { id: user.id }, token } } }
配置需要鑒權(校驗token)的路由
app/router.js
'use strict'; /** * @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller, jwt } = app; router.post('/user/register', controller.user.register); router.post('/user/login', controller.user.login); // 添加日志 需要鑒權 router.post('/diary/add', jwt, controller.diary.add); };
前端頁面調用方式更改:
// 新增日志 axios.post('http://127.0.0.1:7001/diary/add', fieldsValue) .then((res) => { const { data } = res; if(data.code === 200){ message.success(data.message || '操作成功'); }else{ message.error(data.message || '操作失敗'); } }) .catch((err) => { console.log(err); })
改為
// 添加日志 let token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiMTIzIiwiaWF0IjoxNTgzODM5NDk5fQ.aqKI-IN9Os0v197FMKLoJzihg7UrjgMS1s-cWWt7KSM'; axios({ method: 'post', url: 'http://127.0.0.1:7001/diary/add', data: fieldsValue, headers: { Authorization: `Bearer ${token}` } }) .then((res) => { const { data } = res; if(data.code === 200){ message.success(data.message || '操作成功'); }else{ message.error(data.message || '操作失敗'); } }) .catch((err) => { console.log(err); })