跳到导航

身份验证

为事件驱动的 API 建模身份验证方案,如 Bearer、Basic 和 API Key。
以 Markdown 格式查看

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

asyncapi.yml
components:
securitySchemes:
...

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

asyncapi.yml
components:
securitySchemes:
AuthScheme:
...
security:
- AuthScheme: []

Bearer 安全方案

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

asyncapi.yml
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer

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

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

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

asyncapi.yml
components:
securitySchemes:
BearerAuth:
type: http
scheme: bearer
x-fern-token:
name: authToken
env: AUTH_TOKEN

API Key 安全方案

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

asyncapi.yml
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key

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

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

自定义 API Key 变量名称

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

asyncapi.yml
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
x-fern-api-key:
name: customApiKey
env: CUSTOM_API_KEY
in: header
name: X-API-Key

Basic 安全方案

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

asyncapi.yml
components:
securitySchemes:
BasicAuth:
type: http
scheme: basic

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

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

自定义基本认证变量名称

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

asyncapi.yml
components:
securitySchemes:
BasicAuth:
type: http
scheme: basic
x-fern-username:
name: email
env: EMAIL
x-fern-password:
name: pass
env: PASSWORD

OAuth2 安全方案

团队版和企业版功能

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

AsyncAPI 规范支持 OAuth2 身份验证:

asyncapi.yml
components:
securitySchemes:
OAuth2:
type: oauth2
flows:
authorizationCode:
authorizationUrl: https://example.com/oauth/authorize
tokenUrl: https://example.com/oauth/token
scopes:
read: Read access to resources
write: Write access to resources

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

多个安全方案

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

asyncapi.yml
components:
securitySchemes:
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
BearerAuth:
type: http
scheme: bearer
OAuth2:
type: oauth2
flows: ...
operations:
sendMessage:
security:
- ApiKeyAuth: []
- BearerAuth: []

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