jsonwebtoken生成token和解析
先上npm地址
jsonwebtoken:jsonwebtoken - npm
express-jwt:express-jwt - npmps
const express = require('express');
const jwt = require('jsonwebtoken');
const { expressjwt: expressJWT} = require('express-jwt')
const app = express();
// 设置密钥
const secretKey = 'my_secret_key';
// 生成Token
const token = jwt.sign({ username: 'user123' }, secretKey, { expiresIn: '1h' });
// 验证Token1(在req.auth里获取解析值)
app.use(expressJWT({
secret: config.jwtSecretKey,
algorithms:["HS256"],
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring(req) {
if ( req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer" ) {
return req.headers.authorization.split(" ")[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
}
}).unless({ path: ['/api/reguser','/api/login'] }))
//验证Token2
//(这里获取到的token值一定要是jwt生成的token,不能添加其他东西,否则会报incalid Token)
const router = express.Router()
function verifyToken(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(403).json({ code: -1, message: '请登录后再进行操作' });
}
jwt.verify(token, config.jwtSecretKey, (err, decoded) => {
if (err) {
return res.status(500).json({ code: -1, message: 'token验证失败'+err });
}
req.user = decoded;
next();
});
}
router.get('/userinfo',verifyToken, (req, res) => {
res.send(`Welcome ${req.user.username}!`);
});)
// 启动服务器
app.listen(3000, () => {
console.log('Server started on port 3000');
});