jwt在express中token的加密解密实现过程
作者:小灰灰学编程
文章详细介绍了JWT在Node.js中的生成和验证过程,包括设置密钥、使用中间件进行token验证等步骤,并提供了一个完整的示例代码,感兴趣的朋友跟随小编一起看看吧
在我们前面学习了 JWT认证机制在Node.js中的详细阐述 之后,今天来详细学习一下token是如何生成的,secret密钥的加密解密过程是怎么样的。
安装依赖
- express:用于创建服务器
- jsonwebtoken:用于生成和验证JWT
- body-parser:用于解析请求体中的数据
npm install express jsonwebtoken body-parser
设置密钥
SECRET_KEY:用于签名和验证JWT的密钥。请确保在生产环境中使用更安全的方式存储密钥。
// 密钥(请确保在生产环境中使用更安全的方式存储密钥) const SECRET_KEY = 'your_secret_key';
中间件
bodyParser.json():解析请求体。
// 中间件:解析请求体 app.use(bodyParser.urlencoded({extended: false}))
authenticateJWT:验证JWT的中间件。如果验证失败,返回403状态码。
// 中间件:验证JWT const authenticateJWT = (req, res, next) => { const token = req.headers.authorization; if (!token) { return res.sendStatus(403); } jwt.verify(token, SECRET_KEY, (err, user) => { if (err) { return res.sendStatus(403); } console.log(user, 'user') req.user = user; next(); }); };
路由
/register:模拟用户注册并生成JWT。
// 路由:注册用户(示例,仅用于生成token) app.post('/register', (req, res) => { const { username, password } = req.body; // 在实际场景中,您应该验证用户并存储其信息 // 这里仅假设用户验证成功 if (username && password) { // 通过jwt.sign() 生成JWT字符串, // 三个参数分别是:1-用户信息对象(不要把密码进行加密),2-加密密钥,3-配置对象 expiresIn-配置token有效期 const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' }); res.json({ message: 'User registered successfully', token: token }); } else { res.status(400).json({ message: 'Invalid credentials' }); } });
/protected:受保护的路由,需要验证JWT才能访问。
// 路由:受保护的资源 app.get('/protected', authenticateJWT, (req, res) => { res.json({ message: 'This is a protected route', user: req.user }); });
运行服务器
服务器在3000端口运行,你可以通过http://localhost:3000访问。
app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
效果
完整代码
const express = require('express'); const jwt = require('jsonwebtoken'); const bodyParser = require('body-parser'); const app = express(); const port = 3000; // 密钥(请确保在生产环境中使用更安全的方式存储密钥) const SECRET_KEY = 'your_secret_key'; // 中间件:解析请求体 app.use(bodyParser.urlencoded({extended: false})) // 路由:注册用户(示例,仅用于生成token) app.post('/register', (req, res) => { const { username, password } = req.body; // 在实际场景中,您应该验证用户并存储其信息 // 这里仅假设用户验证成功 if (username && password) { // 通过jwt.sign() 生成JWT字符串, // 三个参数分别是:1-用户信息对象(不要把密码进行加密),2-加密密钥,3-配置对象 expiresIn-配置token有效期 const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' }); res.json({ message: 'User registered successfully', token: token }); } else { res.status(400).json({ message: 'Invalid credentials' }); } }); // 中间件:验证JWT const authenticateJWT = (req, res, next) => { console.log(req.headers, 'req.headers') const token = req.headers.authorization; if (!token) { return res.sendStatus(403); } console.log(token, 'token') jwt.verify(token, SECRET_KEY, (err, user) => { if (err) { return res.sendStatus(403); } console.log(user, 'user') req.user = user; next(); }); }; // 路由:受保护的资源 app.get('/protected', authenticateJWT, (req, res) => { res.json({ message: 'This is a protected route', user: req.user }); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
除了 jwt.verify进行token验证之外,还可以使用 express-jwt 中间件。
在Express应用中,express-jwt(现在通常称为express-jwt-ez,因为它是express-jwt的一个更现代、更轻量级的替代品)是一个中间件,用于验证JWT(JSON Web Tokens)。它会自动从请求中提取JWT,并使用提供的密钥或密钥函数来解密(验证)它。如果JWT有效,中间件会将解码后的负载(payload)附加到请求对象上,以便后续的处理程序(handler)可以使用。
安装express-jwt
npm install express-jwt
配置JWT中间件
// 配置JWT中间件 app.use(jwt({ secret: SECRET_KEY, algorithms: ['HS256'] // 指定用于签名JWT的算法(这里使用的是HS256) }).unless({ path: ['/generate-token', /^\/public\//] // 指定哪些路径应该跳过JWT验证(例如,生成token的端点和公共资源的端点) }));
需要注意的是,在使用此方法进行token校验时,Authorization 的value指前面需要包含"Bearer "字符串。
完整代码
const express = require('express'); const expressjwt = require('express-jwt'); const jwt = require('jsonwebtoken'); const app = express(); const port = 3000; // 密钥(请确保在生产环境中使用更安全的方式存储密钥) const SECRET_KEY = 'your_secret_key_here'; // 中间件:解析请求体 app.use(bodyParser.urlencoded({extended: false})) // 配置JWT中间件 app.use(expressjwt({ secret: SECRET_KEY, algorithms: ['HS256'] // 指定用于签名JWT的算法(这里使用的是HS256) }).unless({ path: ['/generate-token', /^\/public\//] // 指定哪些路径应该跳过JWT验证(例如,生成token的端点和公共资源的端点) })); // 路由:生成JWT(这个端点不需要JWT验证) app.post('/generate-token', (req, res) => { const { username } = req.body; if (!username) { return res.status(400).json({ message: 'Username is required' }); } // 生成JWT(在实际应用中,你可能还会包含其他信息,如用户ID、角色等) const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' }); res.json({ message: 'Token generated successfully', token: token }); }); // 路由:受保护的资源(这个端点需要JWT验证) app.get('/protected', (req, res) => { // 如果JWT验证成功,req.auth 将包含解码后的负载(payload) const { username } = req.auth; res.json({ message: 'This is a protected route', user: { username: username } }); }); app.listen(port, () => { console.log(`Server is running on http://localhost:${port}`); });
到此这篇关于jwt在express中token的加密解密实现方法的文章就介绍到这了,更多相关jwt express token加密解密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!