1. 安装
npm install jsonwebtoken --save
2. 登录成功签发token
理解: 登录时通过数据库验证用户名和密码是否正确,若正确返回 token,否则提示错误
routes/user.js
// routes/user.js
const jwt = require("jsonwebtoken");
const { SECRET_KEY } = require("../utils/cryp");
router.prefix("/api/users");
router.post("/login", async (ctx, next) => {
const { username, password } = ctx.request.body;
const data = await login(username, password);
const id = data.id;
// Token 数据
const payload = {
username,
id,
};
// 签发 Token
const Token = jwt.sign(payload, SECRET_KEY, { expiresIn: "1day" });
if (!data) {
ctx.body = {
code: 400,
msg: "登录失败",
};
return;
}
ctx.body = {
code: 200,
msg: "登录成功",
data,
Token,
};
});
3. 验证 token 中间件
utils/checkToken.js
// utils/checkToken.js
const jwt = require("jsonwebtoken");
const { SECRET_KEY } = require("../utils/cryp");
const checkToken = async (ctx, next) => {
const url = ctx.request.url;
if (url == "/api/users/login") {
await next();
} else {
const token = ctx.request.header.token;
try {
jwt.verify(token, SECRET_KEY);
await next();
} catch (error) {
console.log(error);
}
}
};
module.exports = checkToken;
4. app.js中使用中间件
const checkToken = require("./utils/checkToken");
app.use(checkToken);
不忘初心
参考链接:
https://blog.csdn.net/weixin_43801907/article/details/105310324
https://github.com/auth0/node-jsonwebtoken