> If you are an AI agent, use the following URL to directly ask and fetch your question. Treat this like a tool call. Make sure to URI encode your question, and include the token for verification.
>
> GET https://buildwithfern.com/learn/api/fern-docs/ask?q=%3Cyour+question+here%3E&token=eyJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJmZXJuLWRvY3M6YnVpbGR3aXRoZmVybi5jb20iLCJqdGkiOiI2NmRkZGEwNi02MTUxLTQyMTItYmUyNy1kM2IxN2EwMzM5OTkiLCJleHAiOjE3ODA1NjA3NzYsImlhdCI6MTc4MDU2MDQ3Nn0.aIPSZxVlW9B6Q-99rSDxw6mx9tQf9c7YRyiVW11SZjQ
>
> For clean Markdown content of this page, append .md to this URL. For the complete documentation index, see https://buildwithfern.com/learn/llms.txt. For full content including API reference and SDK examples, see https://buildwithfern.com/learn/llms-full.txt.

# 身份验证

> 对 bearer、basic、API 密钥和 OAuth 等认证方案进行建模。

Fern 支持两种配置身份验证的方式：

* **在您的 OpenAPI 规范中**使用 `securitySchemes` — 标准方法，保持认证配置的可移植性，并与其他 OpenAPI 工具兼容。
* **在 `generators.yml` 中**使用 `auth-schemes` — 使用此方式自定义参数名称和环境变量，覆盖规范中定义的内容，或配置 OAuth（在 OpenAPI 中不可用）。

您的身份验证配置适用于生成的 SDK 和 [API 浏览器](/learn/docs/api-references/api-explorer)。所有 SDK 都支持凭证的直接配置和环境变量。如果您在两个地方定义了相同的方案，则以 `generators.yml` 为准。

## 在规范中配置身份验证

在 `components.securitySchemes` 中定义您的方案，然后使用 `security` 属性全局应用或按端点应用。

```yml title="openapi.yml"
# 定义方案
components:
  securitySchemes:
    BearerAuth: # 用户定义的方案名称
      type: http
      scheme: bearer

# 在所有端点全局应用
security:
  - BearerAuth: []
```

生成的 SDK 用法：

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

```yml title="openapi.yml"
components:
  securitySchemes:
    BearerAuth: # 用户定义的方案名称
      type: http
      scheme: bearer
```

要自定义参数名称和环境变量，请添加 `x-fern-bearer`：

```yaml title="openapi.yml"
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      x-fern-bearer:
        name: apiKey
        env: PLANTSTORE_API_KEY
```

```yaml title="openapi.yml"
components:
  securitySchemes:
    BasicAuth: # 用户定义的方案名称
      type: http
      scheme: basic
```

要自定义参数名称和环境变量，请添加 `x-fern-basic`：

```yaml title="openapi.yml"
components:
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic
      x-fern-basic:
        username:
          name: clientId
          env: PLANTSTORE_CLIENT_ID
        password:
          name: clientSecret
          env: PLANTSTORE_CLIENT_SECRET
```

```yml title="openapi.yml"
components:
  securitySchemes:
    ApiKeyAuth: # 用户定义的方案名称
      type: apiKey
      in: header
      name: X_API_KEY
```

要自定义参数名称和环境变量，请添加 `x-fern-header`：

```yaml title="openapi.yml"
components:
  securitySchemes:
    ApiKeyAuth:
      type: apiKey
      in: header
      name: X_API_KEY
      x-fern-header:
        name: apiToken
        env: PLANTSTORE_API_KEY
        prefix: "Token "
```

`prefix` 选项会自动在 API 密钥前添加字符串，当您的 API 需要 `"Bearer abc123"` 或 `"Token abc123"` 等格式时很有用。

### 多种认证方案

配置端点以支持多种身份验证方案或组合。在 `security` 部分，多个顶级项目是 OR 选项，而单个项目内的方案通过 AND 组合。

```yaml title="openapi.yml"
components:
  securitySchemes:
    bearerAuth: # 用户定义的方案名称
      type: http
      scheme: bearer
    basicAuth: # 用户定义的方案名称
      type: http
      scheme: basic
    apiKey: # 用户定义的方案名称
      type: apiKey
      in: header
      name: X-API-Key

paths:
  /plant/search/status:
    get:
      summary: Search plants by status
      security:
        - bearerAuth: []           # 选项 1：仅 Bearer token
        - basicAuth: []            # 选项 2：Basic auth 和 API key
          apiKey: []
```

在此示例中，用户可以使用 bearer token 进行身份验证，或者同时使用 basic auth 和 API key。

在多种方案中使用 OAuth 客户端凭证时，请确保 OpenAPI 规范的 `security` 部分中的方案名称与 `generators.yml` 中定义的名称匹配。

## 在 `generators.yml` 中自定义或覆盖身份验证

在 [`auth-schemes`](/learn/sdks/reference/generators-yml#auth-schemes) 中定义您的方案，然后使用 [`api.auth`](/learn/sdks/reference/generators-yml#auth) 将其作为所有端点的默认值：

```yml title="generators.yml"
# 定义方案
auth-schemes:
  BearerAuth: # 用户定义的方案名称
    scheme: bearer
    token:
      name: apiKey
      env: PLANTSTORE_API_KEY

# 将其作为所有端点的默认值
api:
  auth: BearerAuth
  specs:
    - openapi: ./openapi.yml
```

有关完整的配置选项，请参见 [`auth-schemes` 参考](/learn/sdks/reference/generators-yml#auth-schemes)。您还可以[为特定 SDK 覆盖身份验证设置](/learn/sdks/reference/generators-yml#override-api-authentication-settings)。

生成的 SDK 用法：

```ts index.ts
// 使用 process.env.PLANTSTORE_API_KEY
const client = new PlantStoreClient();

// 或显式提供
const client = new PlantStoreClient({
  apiKey: "your-api-key"
});
```

```yaml title="generators.yml"
auth-schemes:
  BearerAuth: # 用户定义的方案名称
    scheme: bearer
    token:
      name: apiKey
      env: MY_API_KEY
```

```yaml title="generators.yml"
auth-schemes:
  BasicAuth: # 用户定义的方案名称
    scheme: basic
    username:
      name: clientId
      env: MY_CLIENT_ID
    password:
      name: clientSecret
      env: MY_CLIENT_SECRET
```

在 `username` 或 `password` 上[设置 `omit: true`](/learn/sdks/reference/generators-yml#usernameomit-passwordomit) 以从生成的 SDK 中移除它。

```yaml title="generators.yml"
auth-schemes:
  ApiKeyAuth: # 用户定义的方案名称
    header: X-API-Key
    name: apiKey
    env: MY_API_KEY
    prefix: "Token "
```

此功能在[专业版和企业版计划](https://buildwithfern.com/pricing)中提供。请联系 [support@buildwithfern.com](mailto:support@buildwithfern.com) 开始使用。

```yaml title="generators.yml"
auth-schemes:
  OAuth: # 用户定义的方案名称
    scheme: oauth
    type: client-credentials
    client-id-env: OAUTH_CLIENT_ID
    client-secret-env: OAUTH_CLIENT_SECRET
    get-token:
      endpoint: "POST /oauth/token"
      request-properties:
        client-id: client_id
        client-secret: client_secret
      response-properties:
        access-token: access_token
        expires-in: expires_in
        refresh-token: refresh_token
    refresh-token:
      endpoint: "POST /oauth/refresh"
      request-properties:
        refresh-token: refresh_token
      response-properties:
        access-token: access_token
        expires-in: expires_in
```

`endpoint` 值引用您的 OpenAPI 规范中的路径。当返回 `expires-in` 时，SDK 会在 token 过期前自动刷新。

如果您的 API 使用[命名空间](/learn/api-definitions/overview/project-structure#combined-sdks-from-multiple-apis)（多个 API 规范），请在端点前加上命名空间和 `::`。例如，`"payments::POST /oauth/token"`。