保护 Node.js REST API 的编程访问可以通过以下方法实现:
下面是一个使用 JWT 进行身份验证和授权的示例代码:
const jwt = require('jsonwebtoken');
const secretKey = 'your_secret_key';
// 生成 JWT
function generateToken(userId) {
const token = jwt.sign({ userId }, secretKey, { expiresIn: '1h' });
return token;
}
// 验证 JWT
function verifyToken(req, res, next) {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ message: 'No token provided' });
}
jwt.verify(token, secretKey, (err, decoded) => {
if (err) {
return res.status(401).json({ message: 'Invalid token' });
}
req.userId = decoded.userId;
next();
});
}
// 使用身份验证保护 API 路由
app.get('/api/protected', verifyToken, (req, res) => {
// 在这里进行授权访问的逻辑
res.json({ message: 'Protected API route' });
});
// 使用身份验证生成 JWT 并返回给客户端
app.post('/api/login', (req, res) => {
// 在这里进行身份验证逻辑,验证成功后生成 JWT 并返回给客户端
const token = generateToken(userId);
res.json({ token });
});
下面是一个使用 API 密钥进行访问控制的示例代码:
// 定义 API 密钥和对应的访问权限
const apiKeys = {
'client1': 'secret_key_1',
'client2': 'secret_key_2',
};
// 验证 API 密钥
function verifyApiKey(req, res, next) {
const apiKey = req.headers['x-api-key'];
if (!apiKey) {
return res.status(401).json({ message: 'No API key provided' });
}
if (!apiKeys[apiKey]) {
return res.status(401).json({ message: 'Invalid API key' });
}
req.clientId = apiKeys[apiKey];
next();
}
// 使用 API 密钥保护 API 路由
app.get('/api/protected', verifyApiKey, (req, res) => {
// 在这里进行授权访问的逻辑
res.json({ message: 'Protected API route' });
});
以上是保护 Node.js REST API 的编程访问的两种常见方法,你可以根据具体的需求选择适合你的方法。