[TOC]
### 基于JSON WEB TOKEN 封裝 中間件鑒權
1. 導入 jsonwebtoken 包
文檔:[https://www.npmjs.com/package/jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken)
安裝:`npm?install?jsonwebtoken`
*****
2. egg 框架配置
config / config.default.js 中配置 jwt
```
/********** token 配置 **********/
config.jwt = {
secret: 'bcrypt',
expiresIn: 60*60*2 // 2小時過期
}
```
>[danger] secret : token 加密密鑰
> expiresIn:token 有效期
app / extend / context.js 擴展 ctx 屬性
```
const Cryptojs = require('crypto-js');
const jwt = require('jsonwebtoken');
module.exports = {
get jwt() {
return jwt
},
returnSucc(msg='成功', code=0, httpCode=200) {
throw new global.myErrors(msg, code, httpCode)
},
returnError(msg='失敗', code=1, httpCode=400) {
throw new global.myErrors(msg, code, httpCode)
},
crypto(value) {
return Cryptojs.HmacSHA256(value, 'drw_admin888').toString();
}
}
```
*****
3. 配置中間件
app / config / config.default.js
```
/********** 中間件配置 **********/
config.middleware = ['errorHandler', 'auth'];
config.auth = {
allowed: [
'/api/v1/user/register',
'/api/v1/user/login'
]
}
```
>[danger] allowed:不需要token驗證的路由
*****
4. 書寫中間件
app / middleware / auth.js
```
/**
* token 訪問授權
* @param oprions { Array } 配置項:不需要鑒權的路由
* @param app { Object } 當前應用
*/
module.exports = (options, app) => {
return async (ctx, next) => {
// 1.排除不需要驗證 token 的路由
if (options.allowed.indexOf(ctx.request.url) > -1) return await next(options);
//2. 獲取 header 頭token
const { authorization = '' } = ctx.header;
if (!authorization) ctx.returnError('您沒有權限訪問該接口!', 0, 401);
let token = authorization.replace('Bearer ', '')
//3. 根據token解密,換取用戶信息
let user = {};
try {
user = ctx.jwt.verify(token, app.config.jwt.secret)
} catch(err) {
err.name === 'TokenExpiredError' ? ctx.returnError('token 已過期! 請重新獲取令牌')
: ctx.returnError('Token 令牌不合法!');
}
//4. 把 user 信息掛載到全局ctx上
ctx.auth = {
uid: user.uid,
scope: user.scope
}
// 5. 繼續執行
await next(options);
}
}
```
*****
- 概述
- 起步
- 跨域配置
- 路徑別名
- 路由
- api版本控制
- 錯誤和異常
- 全局異常處理
- 數據庫
- 創建遷移文件
- sequelize數據類型
- 配置
- 新增
- 查詢
- 條件查詢
- 模糊查詢
- 排序查詢
- 聚合查詢
- 分組查詢
- 分頁查詢
- 修改
- 刪除
- 獲取器
- 修改器
- 靜態屬性
- 字段驗證
- 外鍵約束
- 關聯模型
- 一對一
- 一對多
- 左外連接
- 多對多
- 字段顯示隱藏
- 事務
- 字段自增
- 驗證層
- egg-validate
- indicative驗證器
- egg-validate-plus
- betterValidate
- 校驗規則
- 中間件
- 安全
- 數據加密
- 單向加密
- 示例代碼
- 封裝egg加密
- 上傳
- path模塊
- 單文件上傳
- 多文件上傳
- 按照日期存儲
- 工具函數
- egg常用工具函數
- 緩存
- 配置緩存插件
- 設置緩存
- 獲取緩存
- 刪除緩存
- 消息隊列
- rabbitMQ
- 安裝
- 簡單隊列
- 工作隊列
- 工作隊列(dispach分發)
- 消息應答和持久化
- redis
- 數據類型
- 字符串類型(String)
- 哈希類型(Hash)
- 列表(List)
- 無序集合(Set)
- 可排序集合(Zset)
- 郵件系統
- nodeMailer
- 第三方模塊
- 生成隨機數
- JWT
- JWT鑒權
- 生成Token
- 短信服務
- 阿里大魚短信驗證碼
- 發送短信邏輯
- 阿里短信Node類