Files
studycode/nodejs/nodeExperiment6/index2.js
2025-12-03 23:08:39 +08:00

57 lines
1.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
const port = 3001;
app.use(bodyParser.json());
// 配置 JWT 相关函数
function generateToken(user) {
// 生成 JWT 令牌
// - { user }: 包含用户信息的对象
// - 'hello kitty': 签名密钥,用于确保 JWT 的完整性
return jwt.sign({ user }, 'hello kitty', { expiresIn: '1h' });
}
// 验证 JWT 令牌
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];// 从请求头中获取 Authorization 字段
const token = authHeader && authHeader.split(' ')[1];// 从 Authorization 字段中提取 JWT 令牌
if (token == null) return res.sendStatus(401);
jwt.verify(token, 'hello kitty', (err, user) => {// 验证 JWT 令牌
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
// 实现用户登录接口JWT
app.post('/jwt-login', (req, res) => {
const { username, password } = req.body;// 从请求体中提取用户名和密码
if (username === 'admin' && password === '123456') {
const user = { id: 1, username };
const accessToken = generateToken(user);// 生成 JWT 令牌
res.json({ accessToken });// 返回包含 JWT 令牌的 JSON 响应
} else {
res.status(401).send('Invalid credentials');
}
});
// 实现用户注销接口JWT
app.post('/jwt-logout', (req, res) => {
res.send('Logged out successfully');
// 注意JWT 本身没有会话管理,客户端需要删除存储的 JWT 令牌
});
// 创建保护路由仅允许已认证用户访问JWT
app.get('/jwt-profile', authenticateToken, (req, res) => {
// 使用 authenticateToken 中间件验证 JWT 令牌
res.send(`Welcome ${req.user.user.username}`);
});
app.listen(port, () => console.log(`JWT Server running on http://localhost:${port}`));