1.0 jwt思路
- 用户输入用户名和密码登录,如果用户名和密码正确的话,使用 jsonwebtoken.sign() 生成 token,并返回给客户端。
- 客户端将token存储在本地存储,在每次的 HTTP 请求中,都将 token 添加在 HTTP Header Authorazition: Bearer token 中。
- 然后后端每次去验证该token的正确与否。只有token正确后才能访问到对应的资源。
1.1 安装依赖
cnpm install jsonwebtoken --save
复制代码
1.2 配置jwt的secret(密钥)
config\config.default.js
config.jwt = {
secret: '我是密钥',
};
复制代码
1.3 用户登录,根据userId
存储jwt
app\controller\home.js
async jwt() {
const { ctx } = this;
const userId = '123456';
const result = await ctx.service.jwt.signJwt(userId);
const data = await ctx.service.jwt.verifyJwt(result);
ctx.body = data;
}
复制代码
1.4 sign签名
- 第一个参数,要加密的数据
- 第二个参数,加密的密钥
- 第三个参数,对象,过期时间
async signJwt(userId) {
const { ctx } = this;
const token = jwt.sign({ userId }, this.config.jwt.secret, {
expiresIn: 60,
});
return token;
}
复制代码
1.5 verify检验`
async verifyJwt(token) {
const { ctx } = this;
try {
let hasToken = false;
const userId = jwt.verify(token, this.config.jwt.secret).userId;
console.log(userId);
if (userId == '123456') {
hasToken = true;
return hasToken;
}
return hasToken;
} catch (err) {
throw (err);
}
}
复制代码