# API 令牌

> Source: https://strapi.nodejs.cn/cms/features/api-tokens

🌐 API Tokens

API 令牌用于在不暴露用户凭据的情况下验证对 Strapi 内容 API 的外部请求。每个令牌都限定在一组权限范围内，并在可配置的时间后过期。

API 令牌允许外部客户端对 Strapi [内容 API](/cms/api/content-api) 的请求进行身份验证。要以编程方式访问管理员面板功能，请参阅 [管理员令牌](/cms/features/admin-tokens)。

🌐 API tokens allow external clients to authenticate requests to the Strapi [Content API](/cms/api/content-api). For programmatic access to the Admin panel features, see [Admin Tokens](/cms/features/admin-tokens).

API 令牌和管理员令牌严格分开：内容 API 令牌在管理员路由上会被拒绝，而管理员令牌在内容 API 路由上会被拒绝。

🌐 API tokens and Admin tokens are strictly separated: a Content API token is rejected on admin routes, and an admin token is rejected on Content API routes.

:::caution Security

对于公共访问，优先使用只读令牌，将令牌的权限限制在你需要的范围内，定期更换长期使用的令牌，并将它们存储在机密管理器中。

🌐 Prefer read-only tokens for public access, scope tokens to only what you need, rotate long-lived tokens, and store them in a secrets manager.

:::

**计划**

免费功能

**角色与权限**

在 角色 > 设置 - API 令牌 中的“访问 API 令牌设置页面”的最低权限

**激活**

默认可用

**环境**

在开发和生产环境中均可用

## 配置 {#configuration}

🌐 Configuration

API 令牌的大多数配置选项都可以在管理面板中使用，并且你的 Strapi 项目的代码可用于更改 API 令牌的生成方式。

🌐 Most configuration options for API tokens are available in the admin panel, and your Strapi project's code can be used to alter how API tokens are generated.

### 管理面板设置 {#admin-panel-settings}

🌐 Admin panel settings

**配置此功能的路径：**  _设置 > 全局设置 > API 令牌_

_API 令牌_ 界面显示一个表格，列出所有已创建的内容 API 令牌。

🌐 The _API Tokens_ interface displays a table listing all created content-api tokens.

从那里，你可以：

🌐 From there, you have the possibility to:

- 点击  以编辑令牌的名称、描述、类型、持续时间或[重新生成令牌](#regenerating-an-api-token)。
- 点击  以删除一个令牌。

:::note

Strapi 会为你预生成 2 个 API 令牌，一个是完全访问令牌，另一个是只读令牌。由于令牌在未配置加密的情况下只能查看一次，你可能希望在设置加密密钥后[重新生成](#regenerating-an-api-token)它们，以便永久可见。

🌐 Strapi pre-generates 2 API tokens for you, a Full access one and a Read-only one. Since tokens can be only seen once without encryption configured, you may want to [regenerate](#regenerating-an-api-token) them after setting up an encryption key to make them permanently viewable.

:::

#### 创建新的 API 令牌 {#creating-a-new-api-token}

🌐 Creating a new API token

1. 点击 **创建新的 API 令牌** 按钮。
2. 在 API 令牌编辑界面，配置新的 API 令牌：

   | 设置名称 | 说明 |
   | -------------- | ------------------------------------------------------------------------ |
   | 名称 | 输入 API 令牌的名称。 |
   | 描述 | （可选）输入 API 令牌的描述。 |
   | 令牌有效期 | 选择令牌有效期：_7 天_、_30 天_、_90 天_ 或 _无限_。 |
   | 令牌类型 | 选择令牌类型：_只读_、_完全访问_ 或 _自定义_。 |

3. （可选）对于 _Custom_ 令牌类型，通过点击内容类型名称并使用复选框启用或禁用权限，为你的 API 端点定义特定权限。
4. 点击 **保存** 按钮。新的 API 令牌将显示在界面顶部，并带有一个复制按钮 。

:::info Viewable tokens

如果在你的 Strapi 项目中配置了加密密钥（`admin.secrets.encryptionKey`），新创建和重新生成的 API 令牌将可以**随时在管理面板中查看**。

🌐 If an encryption key is configured in your Strapi project (`admin.secrets.encryptionKey`), the newly created and regenerated API tokens will be **viewable at any time** in the admin panel.

如果未设置加密密钥，令牌将只能**查看一次**，即在创建或重新生成后立即查看。

🌐 If no encryption key is set, tokens will only be viewable **once**, immediately after creation or regeneration.

:::

#### 重新生成 API 令牌 {#regenerating-an-api-token}

🌐 Regenerating an API token

1. 单击 API 令牌的编辑按钮。
2. 点击 **重新生成** 按钮。
3. 点击 **重新生成** 按钮，在对话框中确认。
4. 复制界面顶部显示的新 API 令牌。

### 基于代码的配置 {#code-based-configuration}

🌐 Code-based configuration

新的 API 令牌是使用盐生成的。该盐由 Strapi 自动生成，并作为 `API_TOKEN_SALT` 存储在环境变量（`.env` 文件）中。

🌐 New API tokens are generated using a salt. This salt is automatically generated by Strapi and stored in environment variables (the `.env` file) as `API_TOKEN_SALT`.

盐可以定制：

🌐 The salt can be customized:

- 可以通过在[your `/config/admin` 文件](/cms/configurations/admin-panel)中更新 `apiToken.salt` 的字符串值来实现
- 或者通过在项目的 `.env` 文件中创建一个 `API_TOKEN_SALT` [环境变量](/cms/configurations/environment#strapi)

:::caution

更改盐会使所有现有的 API 令牌失效。

🌐 Changing the salt invalidates all the existing API tokens.

:::

#### 确保 API 令牌在管理面板中可见 {#ensuring-api-tokens-are-visible-in-the-admin-panel}

🌐 Ensuring API tokens are visible in the admin panel

要在管理面板中允许 API 令牌的持久可见性，必须在[your `/config/admin` 文件](/cms/configurations/admin-panel)的 `secrets.encryptionKey` 下提供加密密钥：

🌐 To allow persistent visibility of API tokens in the admin panel, an encryption key must be provided in [your `/config/admin` file](/cms/configurations/admin-panel) under `secrets.encryptionKey`:

```js title="/config/admin.js"
module.exports = ({ env }) => ({
  // other config parameters
  secrets: {
    encryptionKey: env('ENCRYPTION_KEY'),
  }
});
```

```ts title="/config/admin.ts"

  // other config parameters
  secrets: {
    encryptionKey: env('ENCRYPTION_KEY'),
  }
});
```

此密钥用于加密和解密令牌值。没有此密钥，令牌仍然可以使用，但在初次显示后将无法查看。新的 Strapi 项目将自动生成此密钥。

🌐 This key is used to encrypt and decrypt token values. Without this key, tokens remain usable, but will not be viewable after initial display. New Strapi projects will have this key automatically generated.

:::tip

对于需要以编程方式调用管理员面板功能的自动化工作流，请改用管理员令牌。完整文档请参见 [管理员令牌](/cms/features/admin-tokens)。

🌐 For automation workflows that need to call the Admin panel features programmatically, use admin tokens instead. See [Admin Tokens](/cms/features/admin-tokens) for the full documentation.

:::

## 使用 {#usage}

🌐 Usage

使用 API 令牌可以以经过身份验证的用户身份在 [REST API](/cms/api/rest) 或 [GraphQL API](/cms/api/graphql) 端点上执行请求。

🌐 Using API tokens allows executing a request on [REST API](/cms/api/rest) or [GraphQL API](/cms/api/graphql) endpoints as an authenticated user.

API 令牌有助于授予人员或应用访问权限，而无需管理用户账户或更改用户和权限插件中的任何内容。

🌐 API tokens can be helpful to give access to people or applications without managing a user account or changing anything in the Users & Permissions plugin.

在向 Strapi 的 REST API 执行请求时，API 令牌应以以下语法添加到请求的 `Authorization` 头中：`bearer your-api-token`。

🌐 When performing a request to Strapi's REST API, the API token should be added to the request's `Authorization` header with the following syntax: `bearer your-api-token`.

:::note

只读 API 令牌只能访问 `find` 和 `findOne` 功能。

🌐 Read-only API tokens can only access the `find` and `findOne` functions.

:::
