authorization.js 987 B

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