authorization.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  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. console.log(22, req.headers.authorization);
  20. if(!req.headers.authorization) {
  21. return res.status(401).json({ code: "401", msg: "token无效" });
  22. }
  23. const token = req.headers.authorization.split(" ")[1];
  24. jwt.verify(token, secretKey, function (err, decoded) {
  25. if (err) {
  26. console.log("verify error", err);
  27. return res.status(401).json({ code: "401", msg: "token无效" });
  28. }
  29. req.body.userInfo = decoded
  30. next();
  31. });
  32. }