在Linux上使用Swagger進行API的安全認證,通常涉及以下幾個步驟:
首先,你需要在你的Linux系統上安裝Swagger。你可以使用npm(Node.js的包管理器)來安裝Swagger。
sudo npm install -g swagger-jsdoc swagger-ui-express
創建一個Swagger配置文件,通常是swagger.json
或swagger.yaml
。這個文件定義了你的API規范,包括路徑、方法、參數和響應等。
swagger.json
{
"swagger": "2.0",
"info": {
"description": "Sample API",
"version": "1.0.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"https"
],
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"responses": {
"200": {
"description": "A list of users"
}
}
},
"post": {
"summary": "Create a new user",
"parameters": [
{
"name": "user",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"responses": {
"201": {
"description": "User created successfully"
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
},
"required": ["id", "name"]
}
}
}
在你的Express應用中集成Swagger UI。
app.js
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
const port = 3000;
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.get('/users', (req, res) => {
res.json([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]);
});
app.post('/users', (req, res) => {
const user = req.body;
// Save user to database
res.status(201).json({ message: 'User created successfully', user });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
Swagger支持多種安全認證方式,包括API密鑰、OAuth 2.0、JWT等。以下是使用API密鑰的示例。
{
"swagger": "2.0",
"info": {
"description": "Sample API",
"version": "1.0.0"
},
"host": "api.example.com",
"basePath": "/v1",
"schemes": [
"https"
],
"securityDefinitions": {
"apiKey": {
"type": "apiKey",
"in": "header",
"name": "X-API-KEY"
}
},
"paths": {
"/users": {
"get": {
"summary": "Get all users",
"security": [
{
"apiKey": []
}
],
"responses": {
"200": {
"description": "A list of users"
}
}
},
"post": {
"summary": "Create a new user",
"parameters": [
{
"name": "user",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/User"
}
}
],
"security": [
{
"apiKey": []
}
],
"responses": {
"201": {
"description": "User created successfully"
}
}
}
}
},
"definitions": {
"User": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
}
},
"required": ["id", "name"]
}
}
}
你可以使用中間件來驗證API密鑰。
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');
const app = express();
const port = 3000;
const apiKey = 'your-secret-api-key';
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const authenticateApiKey = (req, res, next) => {
const apiKeyHeader = req.header('X-API-KEY');
if (apiKeyHeader === apiKey) {
next();
} else {
res.status(401).json({ message: 'Invalid API key' });
}
};
app.get('/users', authenticateApiKey, (req, res) => {
res.json([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
]);
});
app.post('/users', authenticateApiKey, (req, res) => {
const user = req.body;
// Save user to database
res.status(201).json({ message: 'User created successfully', user });
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
最后,運行你的Express應用。
node app.js
現在,你可以通過訪問http://localhost:3000/api-docs
來查看Swagger UI,并測試你的API。確保在請求頭中包含X-API-KEY
來進行認證。
通過以上步驟,你可以在Linux上使用Swagger進行API的安全認證。