123456789101112131415161718192021222324252627282930313233 |
- import jwt from "jsonwebtoken";
- import environment from "#environment";
- const secretKey = "secretKey";
- // 生成token
- export function generateToken(payload) {
- const token =
- "Bearer " +
- jwt.sign(payload, secretKey, {
- // expiresIn: 60 * 60 * 24 * 7 * 4 * 12, // 一年过期
- // expiresIn: 60 * 60 * 24 * 7 * 4, // 一个月
- expiresIn: 60 * 60 * 24 * 7, // 一周
- // expiresIn: 60 * 60 * 24, // 一天
- // expiresIn: 60 * 60, // 一个小时
- }, environment.privateKey, { algorithm: 'RS256' });
- return token;
- }
- // 验证token
- export function verifyToken(req, res, next) {
- if(!req.headers.authorization) {
- return res.status(401).json({ code: "401", msg: "token无效" });
- }
- const token = req.headers.authorization.split(" ")[1];
- jwt.verify(token, secretKey, function (err, decoded) {
- if (err) {
- return res.status(401).json({ code: "401", msg: "token无效" });
- }
- req.body.userInfo = decoded
- next();
- });
- }
|