authorization.js 984 B

123456789101112131415161718192021222324252627282930313233
  1. import jwt from "jsonwebtoken";
  2. import environment from "#environment";
  3. const secretKey = "secretKey";
  4. // 生成token
  5. export function generateToken(payload) {
  6. const token =
  7. "Bearer " +
  8. jwt.sign(payload, secretKey, {
  9. // expiresIn: 60 * 60 * 24 * 7 * 4 * 12, // 一年过期
  10. // expiresIn: 60 * 60 * 24 * 7 * 4, // 一个月
  11. expiresIn: 60 * 60 * 24 * 7, // 一周
  12. // expiresIn: 60 * 60 * 24, // 一天
  13. // expiresIn: 60 * 60, // 一个小时
  14. }, environment.privateKey, { algorithm: 'RS256' });
  15. return token;
  16. }
  17. // 验证token
  18. export function verifyToken(req, res, next) {
  19. if(!req.headers.authorization) {
  20. return res.status(401).json({ code: "401", msg: "token无效" });
  21. }
  22. const token = req.headers.authorization.split(" ")[1];
  23. jwt.verify(token, secretKey, function (err, decoded) {
  24. if (err) {
  25. return res.status(401).json({ code: "401", msg: "token无效" });
  26. }
  27. req.body.userInfo = decoded
  28. next();
  29. });
  30. }