在Linux环境下为Swagger API添加安全认证,可以确保只有授权用户才能访问API文档。以下是实现这一目标的详细步骤:
首先,确保你的Linux系统上已经安装了Swagger。你可以使用npm(Node.js的包管理器)来安装Swagger。
npm install -g swagger-ui-express
创建一个Swagger配置文件(通常是swagger.json
),定义你的API规范。
{
"swagger": "2.0",
"info": {
"description": "Sample API",
"version": "1.0.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"https"
],
"paths": {
"/users": {
"get": {
"summary": "List all users",
"responses": {
"200": {
"description": "A list of users"
}
}
},
"post": {
"summary": "Create a new user",
"responses": {
"201": {
"description": "User created"
}
}
}
}
}
}
Swagger支持多种安全方案,包括基本认证、OAuth2、API密钥等。以下是一个使用基本认证的示例。
首先,安装Passport和Passport Basic模块。
npm install passport passport-basic
在你的应用中配置Passport以使用基本认证。
const express = require('express');
const passport = require('passport');
const BasicStrategy = require('passport-basic').Strategy;
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.json');
const app = express();
// Passport configuration
passport.use(new BasicStrategy(
function(username, password, done) {
if (username === 'admin' && password === 'secret') {
return done(null, { username: 'admin' });
} else {
return done(null, false);
}
}
));
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(username, done) {
done(null, { username: username });
});
app.use(passport.initialize());
// Swagger UI setup
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
// Protected route
app.get('/protected', passport.authenticate('basic', { session: false }), (req, res) => {
res.json({ message: 'This is a protected route' });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
启动你的Node.js应用。
node app.js
你可以使用Postman或其他API测试工具来测试认证。在请求头中添加Authorization: Basic YWRtaW46c2VjcmV0
(这是admin:secret
的Base64编码),然后访问受保护的路由。
除了基本认证,Swagger还支持OAuth2和API密钥认证。以下是这两种认证方式的简要说明:
swagger.yaml
或swagger.json
)中添加OAuth2安全方案定义。securityDefinitions:
oauth2:
type: oauth2
flow: accessCode
authorizationUrl: https://your-oauth-server/oauth/authorize
tokenUrl: https://your-oauth-server/oauth/token
scopes:
read: Grants read access
write: Grants write access
paths:
/protected-resource:
get:
security:
- oauth2: []
securityDefinitions:
apiKeyAuth:
type: apiKey
in: header
name: X-API-KEY
paths:
/protected-resource:
get:
security:
- apiKeyAuth: