溫馨提示×

如何在Linux上配置Swagger的認證授權

小樊
44
2025-10-13 15:47:10
欄目: 智能運維

在Linux上配置Swagger的認證授權,通常涉及到幾個步驟。以下是一個基本的指南,假設你已經安裝了Swagger UI和相關的Swagger工具。

1. 安裝Swagger UI

首先,確保你已經安裝了Swagger UI。你可以使用npm來安裝Swagger UI:

npm install -g swagger-ui-express

2. 創建一個簡單的Express應用

創建一個新的Express應用,并集成Swagger UI:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();
const port = 3000;

// Load Swagger document
const swaggerDocument = YAML.load('./swagger.yaml');

// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

3. 配置認證授權

Swagger支持多種認證方式,包括基本認證、OAuth2、API密鑰等。以下是一個使用基本認證的示例:

3.1 安裝基本認證中間件

你可以使用express-basic-auth中間件來實現基本認證:

npm install express-basic-auth

3.2 配置基本認證

在你的Express應用中配置基本認證:

const basicAuth = require('express-basic-auth');

const users = {
  'user1': 'password1',
  'user2': 'password2'
};

app.use(basicAuth({
  users: users,
  challenge: true,
  unauthorizedResponse: {
    'WWW-Authenticate': 'Basic realm="example"',
    'Content-Type': 'text/html',
    'Content-Length': '0'
  }
}));

// Serve Swagger docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(port, () => {
  console.log(`Server is running at http://localhost:${port}`);
});

4. 配置Swagger文檔

在你的swagger.yaml文件中添加認證授權信息:

swagger: '2.0'
info:
  title: Sample API
  description: A sample API with authentication
  version: '1.0.0'
host: localhost:3000
basePath: /
schemes:
  - http
paths:
  /api/resource:
    get:
      summary: Get a resource
      responses:
        '200':
          description: Successful response
      security:
        - basicAuth: []
components:
  securitySchemes:
    basicAuth:
      type: basic

5. 運行應用

現在你可以運行你的Express應用:

node app.js

訪問http://localhost:3000/api-docs,你應該會看到Swagger UI界面,并且需要進行基本認證才能訪問API文檔。

其他認證方式

如果你需要使用其他認證方式(如OAuth2、API密鑰等),可以參考Swagger的官方文檔來配置相應的認證方案。

參考文檔

通過以上步驟,你可以在Linux上配置Swagger的認證授權。

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