请使用node.js和express-jwt写一份完整token处理以及中间件
时间: 2024-06-12 09:05:46 浏览: 200
以下是一个使用Node.js和express-jwt的完整Token处理和中间件的示例:
1. 安装必要的依赖
```
npm install express express-jwt jsonwebtoken
```
2. 创建一个JWT密钥
```
const jwtSecret = 'mysecretkey';
```
3. 创建一个函数来生成令牌
```
const jwt = require('jsonwebtoken');
function generateToken(user) {
const payload = {
sub: user.id,
iat: Date.now()
};
const options = {
expiresIn: '1d'
};
return jwt.sign(payload, jwtSecret, options);
}
```
4. 创建一个路由来登录并生成令牌
```
const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.post('/login', (req, res) => {
const { email, password } = req.body;
User.findOne({ email: email }, (err, user) => {
if (err) {
return res.status(500).json({ error: err });
}
if (!user) {
return res.status(401).json({ error: 'User not found' });
}
if (!user.validPassword(password)) {
return res.status(401).json({ error: 'Invalid password' });
}
const token = generateToken(user);
res.json({ token });
});
});
module.exports = router;
```
5. 创建一个中间件来验证令牌
```
const jwt = require('express-jwt');
function getTokenFromHeader(req) {
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
return req.headers.authorization.split(' ')[1];
}
return null;
}
const auth = {
required: jwt({
secret: jwtSecret,
userProperty: 'payload',
getToken: getTokenFromHeader
}),
optional: jwt({
secret: jwtSecret,
userProperty: 'payload',
getToken: getTokenFromHeader,
credentialsRequired: false
})
};
module.exports = auth;
```
6. 使用验证令牌的中间件保护路由
```
const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
router.get('/protected', auth.required, (req, res) => {
res.json({ message: 'You are authorized to access this protected route' });
});
router.get('/optional', auth.optional, (req, res) => {
res.json({ message: 'This route can be accessed without a token' });
});
module.exports = router;
```
现在,你可以使用这些路由来生成令牌、保护受保护的路由并允许可选的路由。
阅读全文