在CentOS上使用Node.js实现API接口鉴权,通常采用JSON Web Tokens (JWT) 或 OAuth 2.0等方案。以下是使用JWT进行API接口鉴权的步骤:
安装Node.js和npm(如果尚未安装): CentOS 7:
sudo yum install -y nodejs npm
CentOS 8:
sudo dnf install -y nodejs npm
创建一个新的Node.js项目:
mkdir my_api_project
cd my_api_project
npm init -y
安装所需的npm包:
npm install express jsonwebtoken bcryptjs body-parser --save
创建一个名为app.js
的文件,并编写以下代码:
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
// 用于签发JWT的密钥
const JWT_SECRET = 'your_jwt_secret';
// 模拟用户数据
const users = [
{
id: 1,
username: 'user1',
password: bcrypt.hashSync('password1', 8)
}
];
// 登录接口
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (user && bcrypt.compareSync(password, user.password)) {
const token = jwt.sign({ id: user.id, username: user.username }, JWT_SECRET, { expiresIn: '1h' });
res.json({ message: '登录成功', token });
} else {
res.status(401).json({ message: '用户名或密码错误' });
}
});
// 鉴权中间件
const auth = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(403).json({ message: '没有提供token' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({ message: 'token无效或已过期' });
}
};
// 受保护的API接口
app.get('/protected', auth, (req, res) => {
res.json({ message: '这是一个受保护的API接口,你已经通过鉴权' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
运行Node.js应用:
node app.js
现在,你可以使用Postman或其他API测试工具来测试登录接口和保护API接口。首先,通过发送用户名和密码到/login
接口来获取JWT。然后,在请求受保护的API接口时,在HTTP头中添加Authorization: Bearer <token>
,其中<token>
是从登录接口获得的JWT。