课程代码
This commit is contained in:
36
nodejs/nodeExperiment6/.gitignore
vendored
Normal file
36
nodejs/nodeExperiment6/.gitignore
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
*.tsbuildinfo
|
||||
|
||||
.eslintcache
|
||||
|
||||
# Cypress
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Vitest
|
||||
__screenshots__/
|
||||
65
nodejs/nodeExperiment6/index.js
Normal file
65
nodejs/nodeExperiment6/index.js
Normal file
@@ -0,0 +1,65 @@
|
||||
const express = require('express');
|
||||
const session = require('express-session');
|
||||
const bodyParser = require('body-parser');
|
||||
|
||||
const app = express();
|
||||
const port = 3000;
|
||||
|
||||
// 设置中间件
|
||||
app.use(bodyParser.urlencoded({ extended: false }));
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// 配置 session 中间件
|
||||
app.use(session({
|
||||
secret: 'hello kitty',
|
||||
resave: false,
|
||||
saveUninitialized: true,
|
||||
cookie: { secure: false } // 在生产环境中设置为 true
|
||||
}));
|
||||
|
||||
|
||||
// 创建登录接口
|
||||
app.post('/login', (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (username === 'admin' && password === '123456') {
|
||||
req.session.user = { id: 1, username };
|
||||
res.send('User logged in');
|
||||
} else {
|
||||
res.status(401).send('Invalid credentials');
|
||||
}
|
||||
});
|
||||
|
||||
// 创建注销接口
|
||||
app.post('/logout', (req, res) => {
|
||||
req.session.destroy((err) => {
|
||||
if (err) {
|
||||
return res.status(500).send('Could not log out.');
|
||||
}
|
||||
res.send('Logout successful');
|
||||
});
|
||||
});
|
||||
|
||||
// 认证中间件
|
||||
function isAuthenticated(req, res, next) {
|
||||
if (req.session.user) {
|
||||
next();
|
||||
} else {
|
||||
res.status(401).send('You are not authenticated!');
|
||||
}
|
||||
}
|
||||
|
||||
// 创建保护路由
|
||||
app.get('/protected', isAuthenticated, (req, res) => {
|
||||
res.send('This is a protected route');
|
||||
});
|
||||
|
||||
// 实现基于 Session 的身份认证机制
|
||||
app.get('/profile', isAuthenticated, (req, res) => {
|
||||
res.send(`Welcome ${req.session.user.username}`);
|
||||
});
|
||||
|
||||
|
||||
app.listen(port, () => {
|
||||
console.log(`Server is running on http://localhost:${port}`);
|
||||
});
|
||||
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}`));
|
||||
1019
nodejs/nodeExperiment6/package-lock.json
generated
Normal file
1019
nodejs/nodeExperiment6/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
20
nodejs/nodeExperiment6/package.json
Normal file
20
nodejs/nodeExperiment6/package.json
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"name": "nodeexperiment6",
|
||||
"version": "1.0.0",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
"start": "node index.js",
|
||||
"dev": "nodemon index.js",
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"body-parser": "^2.2.1",
|
||||
"express": "^5.1.0",
|
||||
"express-session": "^1.18.2",
|
||||
"jsonwebtoken": "^9.0.2"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user