egg-jwt配置

1. 安裝
npm i egg-jwt --save

 
2.config/config.default
    config.jwt = {
secret: appInfo.name + '_1539582326426_4353',
unless: {
path:
}
};

 
3.config/plugin
exports.jwt = {
enable: true,
package: "egg-jwt"
};

 4.service/apps/jwt.js
class jwtService extends Service {
constructor(ctx) {
super(ctx)
};
// jwt 加密 使用HS256
/**
*
* @param {Object} parmas 需封装的参数
* @param {String} type 类型 default:'web' ->24hrs
* @param {Boolean} expires 是否设置过期 default:true
*/
async sign(parmas, type = 'web', expires = true) {
const app = this.app;
return await app.jwt.sign({ ...parmas }, app.config.jwt.secret, { algorithm: 'HS256', ...(expires && { expiresIn: `${type === 'web' ? '24 hrs' : '30 days'}` }) })
}
// JWT 解密
async verify(token) {
const { app } = this;
return await app.jwt.verify(token, app.config.jwt.secret, { algorithm: 'HS256' })
}
}
module.exports = jwtService
5.使用
class weChatTemplateService extends indexService {
constructor(ctx) {
super(ctx);
this.userMODEL = ctx.model.Account.User;
this.tokenSERVICE = ctx.service.account.jwt
};
...
setToken(params, other) {
return { 'token': this.tokenSERVICE.create(params), ...other }
};
...
}
6.鑒權
egg-jwt已经封装了verify 不需要再做 verify
获取token 数据 使用 this.ctx.state.user 获取
亦可在context封装鉴权
/extend/context
module.exports = {
isAdmin() {
return this.state.user.group === 1 ? false : true;
},
_uid() {
return this.state.user._id
}
};
在controller 下面可以直接用
ctx.isAdmin() ctx._uid() 来获取

0 个评论

要回复文章请先登录注册