统一身份认证系统




{`
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
const secret = 'your_secret_key'; // 用于签名的密钥
// 模拟用户数据库
const users = [
{ id: 1, username: 'alice', password: 'password' },
{ id: 2, username: 'bob', password: 'password' }
];
// 登录接口
app.post('/login', (req, res) => {
const user = users.find(u => u.username === req.body.username && u.password === req.body.password);
if (user) {
const token = jwt.sign({ id: user.id }, secret, { expiresIn: '1h' });
res.json({ success: true, token: token });
} else {
res.status(400).json({ success: false, message: 'Invalid credentials' });
}
});
// 需要身份验证的接口
app.get('/protected', (req, res) => {
try {
const decoded = jwt.verify(req.headers.authorization.split(' ')[1], secret);
res.json({ message: 'Welcome!', user: decoded });
} catch (err) {
res.status(401).json({ message: 'Unauthorized' });
}
});
app.listen(3000, () => console.log('Server running on port 3000'));
`}