溫馨提示×

如何在Linux上使用Swagger進行API的安全認證

小樊
45
2025-08-15 03:55:01
欄目: 智能運維

在Linux上使用Swagger進行API的安全認證,通常涉及以下幾個步驟:

1. 安裝Swagger

首先,你需要在你的Linux系統上安裝Swagger。你可以使用npm(Node.js的包管理器)來安裝Swagger。

sudo npm install -g swagger-jsdoc swagger-ui-express

2. 創建Swagger配置文件

創建一個Swagger配置文件,通常是swagger.jsonswagger.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"]
    }
  }
}

3. 集成Swagger到Express應用

在你的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}`);
});

4. 配置安全認證

Swagger支持多種安全認證方式,包括API密鑰、OAuth 2.0、JWT等。以下是使用API密鑰的示例。

在Swagger配置文件中添加安全方案

{
  "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"]
    }
  }
}

在Express應用中驗證API密鑰

你可以使用中間件來驗證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}`);
});

5. 運行應用

最后,運行你的Express應用。

node app.js

現在,你可以通過訪問http://localhost:3000/api-docs來查看Swagger UI,并測試你的API。確保在請求頭中包含X-API-KEY來進行認證。

通過以上步驟,你可以在Linux上使用Swagger進行API的安全認證。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女