课程代码
This commit is contained in:
57
nodejs/nodeExperiment6/index2.js
Normal file
57
nodejs/nodeExperiment6/index2.js
Normal file
@@ -0,0 +1,57 @@
|
||||
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}`));
|
||||
Reference in New Issue
Block a user