身份验证

为事件驱动的 API 建模身份验证方案,如 Bearer、Basic 和 API Key。

以 Markdown 格式查看

身份验证方案的配置在 AsyncAPI 的 components.securitySchemes 部分中进行。

asyncapi.yml
1components:
2 securitySchemes:
3 ...

要在所有操作中应用安全方案,请在 AsyncAPI 规范的 security 部分引用 securityScheme

asyncapi.yml
1components:
2 securitySchemes:
3 AuthScheme:
4 ...
5security:
6 - AuthScheme: []

Bearer 安全方案

首先在 asyncapi.yml 中定义一个 bearer 安全方案:

asyncapi.yml
1components:
2 securitySchemes:
3 BearerAuth:
4 type: http
5 scheme: bearer

这将生成一个 SDK,用户需要提供一个名为 token 的必需参数。

index.ts
1const client = new Client({
2 token: "ey34..."
3})

如果你想控制变量命名和要扫描的环境变量,请使用以下配置:

asyncapi.yml
1components:
2 securitySchemes:
3 BearerAuth:
4 type: http
5 scheme: bearer
6 x-fern-token:
7 name: authToken
8 env: AUTH_TOKEN

API Key 安全方案

首先在 asyncapi.yml 中定义一个 apiKey 安全方案:

asyncapi.yml
1components:
2 securitySchemes:
3 ApiKeyAuth:
4 type: apiKey
5 in: header
6 name: X-API-Key

这将生成一个 SDK,用户需要提供一个名为 apiKey 的必需参数。

index.ts
1const client = new Client({
2 apiKey: "my-api-key"
3})

自定义 API Key 变量名称

如果你想控制变量命名和要扫描的环境变量,请使用以下配置:

asyncapi.yml
1components:
2 securitySchemes:
3 ApiKeyAuth:
4 type: apiKey
5 x-fern-api-key:
6 name: customApiKey
7 env: CUSTOM_API_KEY
8 in: header
9 name: X-API-Key

Basic 安全方案

首先在 asyncapi.yml 中定义一个 basic 安全方案:

asyncapi.yml
1components:
2 securitySchemes:
3 BasicAuth:
4 type: http
5 scheme: basic

这将生成一个 SDK,用户需要提供 usernamepassword

index.ts
1const client = new Client({
2 username: "john@example.com",
3 password: "password123"
4})

自定义基本认证变量名称

如果你想控制变量命名和要扫描的环境变量,请使用以下配置:

asyncapi.yml
1components:
2 securitySchemes:
3 BasicAuth:
4 type: http
5 scheme: basic
6 x-fern-username:
7 name: email
8 env: EMAIL
9 x-fern-password:
10 name: pass
11 env: PASSWORD

OAuth2 安全方案

团队版、专业版和企业版功能

此功能仅适用于团队版(文档)、专业版(SDK)和企业版计划。要开始使用,请联系 support@buildwithfern.com

AsyncAPI 规范支持 OAuth2 身份验证:

asyncapi.yml
1components:
2 securitySchemes:
3 OAuth2:
4 type: oauth2
5 flows:
6 authorizationCode:
7 authorizationUrl: https://example.com/oauth/authorize
8 tokenUrl: https://example.com/oauth/token
9 scopes:
10 read: Read access to resources
11 write: Write access to resources

这将生成一个支持事件驱动操作的 OAuth2 流程的 SDK。

多个安全方案

你可以指定多个安全方案并将它们应用于不同的操作:

asyncapi.yml
1components:
2 securitySchemes:
3 ApiKeyAuth:
4 type: apiKey
5 in: header
6 name: X-API-Key
7 BearerAuth:
8 type: http
9 scheme: bearer
10 OAuth2:
11 type: oauth2
12 flows: ...
13
14operations:
15 sendMessage:
16 security:
17 - ApiKeyAuth: []
18 - BearerAuth: []

这允许不同的操作根据需要使用不同的身份验证方法。