在Linux上配置Swagger的認證授權,通常涉及到幾個步驟。以下是一個基本的指南,假設你已經安裝了Swagger UI和相關的Swagger工具。
首先,確保你已經安裝了Swagger UI。你可以使用npm來安裝Swagger UI:
npm install -g swagger-ui-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}`);
});
Swagger支持多種認證方式,包括基本認證、OAuth2、API密鑰等。以下是一個使用基本認證的示例:
你可以使用express-basic-auth
中間件來實現基本認證:
npm install express-basic-auth
在你的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}`);
});
在你的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
現在你可以運行你的Express應用:
node app.js
訪問http://localhost:3000/api-docs
,你應該會看到Swagger UI界面,并且需要進行基本認證才能訪問API文檔。
如果你需要使用其他認證方式(如OAuth2、API密鑰等),可以參考Swagger的官方文檔來配置相應的認證方案。
通過以上步驟,你可以在Linux上配置Swagger的認證授權。