# 用户与权限

> Source: https://strapi.nodejs.cn/cms/features/users-permissions

🌐 Users & Permissions

用户与权限管理终端用户账户、基于JWT的身份验证以及基于角色的API访问权限。本文档解释了如何创建角色、配置权限以及保护对内容API的访问。

“用户与权限”功能允许管理 Strapi 项目的终端用户 💡 **什么是终端用户？** <br/> 终端用户是使用 Strapi 应用创建和管理的内容，并在前端应用（如网站、移动应用、连接设备等）上展示的用户。与管理员不同，他们无法访问管理面板。 它提供基于 JSON Web Token（JWT）的完整身份验证流程来保护你的 API，并且提供访问控制列表（ACL）策略，使你能够管理用户组之间的权限。

**计划**

免费功能

**角色与权限**

角色 > 插件 - 用户与权限中的 CRUD 权限

**激活**

默认可用

**环境**

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

## 管理面板配置 {#admin-panel-configuration}

🌐 Admin panel configuration

用户和权限功能可从管理面板设置和代码库进行配置。

🌐 The Users & Permissions feature is configured from both the admin panel settings, and via the code base.

### 角色 {#roles}

🌐 Roles

“用户与权限”功能允许为终端用户创建和管理角色，以配置他们可以访问的内容。

🌐 The Users & Permissions feature allows creating and managing roles for end users, to configure what they can have access to.

#### 创建新角色 {#creating-a-new-role}

🌐 Creating a new role

**路径:**  *用户与权限插件 > 角色*

在 *Roles* 界面的右上角，会显示一个 **Add new role** 按钮。它允许为你的 Strapi 应用的终端用户创建一个新角色。

🌐 On the top right side of the *Roles* interface, an **Add new role** button is displayed. It allows creating a new role for end users of your Strapi application.

点击 **添加新角色** 按钮，将会跳转到角色编辑界面，在那里你可以为新角色命名并定义其详细信息和权限（参见 [编辑角色](#editing-a-role)）。

🌐 Click on the **Add new role** button to be redirected to the roles edition interface, where you will be able to name your new role and define its details and permissions (see [Editing a role](#editing-a-role)).

:::note

所有新终端用户默认分配的终端用户角色可以在*用户与权限插件*的*高级设置*子部分中定义（参见[高级设置](#advanced-settings)）。

🌐 The end-user role attributed by default to all new end users can be defined in the *Advanced settings* sub-section of *Users & Permissions plugin* (see [Advanced settings](#advanced-settings)).

:::

#### 编辑角色 {#editing-a-role}

🌐 Editing a role

**路径:**  *用户与权限插件 > 角色*

*Roles* 界面显示为你的 Strapi 应用的终端用户创建的所有角色。

🌐 The *Roles* interface displays all created roles for the end users of your Strapi application.

默认情况下，为任何 Strapi 应用定义 2 个终端用户角色：

🌐 By default, 2 end-user roles are defined for any Strapi application:

- 已认证：只有在登录前端应用的情况下，终端用户才能访问内容。
- 公共：供终端用户在未登录前端应用的情况下访问内容。

然而，可以创建更多角色（参见[创建新角色](#creating-a-new-role)），并且所有角色都可以通过角色编辑界面进行编辑。

🌐 More roles can however be created (see [Creating a new role](#creating-a-new-role)), and all can be edited through the role edition interface.

1. 点击角色的编辑按钮  进行编辑。如果你是从创建新角色直接进入角色编辑界面，则跳过此步骤。
2. 填写*角色详情*，按照下表中的说明操作：

| 角色详情 | 指示 |
| --- | --- |
| 名称 | 在文本框中写下角色的新名称。 |
| 描述 | 在文本框中写下角色的描述。它应该帮助管理员了解该角色可以访问的内容。 |

3. 通过以下方式配置终端用户角色的*权限*：
    1. 单击要配置的权限类别的名称（例如应用、内容管理器、电子邮件等）。
    2. 勾选要授予角色的操作和权限的框。
4. 点击 **保存** 按钮。

:::tip

当勾选某个操作或权限框时，界面右侧会显示该 API 的相关绑定路由。

🌐 When ticking an action or permission box, related bound routes of the API are displayed in the right side of the interface.

:::

#### 删除角色 {#deleting-a-role}

🌐 Deleting a role

**路径:**  *用户与权限插件 > 角色*

虽然公共角色不能被删除，但其他角色可以被删除。当前分配到已删除角色的用户将自动重新分配到公共角色。

🌐 Although the Public role cannot be deleted, other roles can be deleted. Users currently assigned to a deleted role are automatically reassigned to the Public role.

1. 点击角色记录右侧的删除按钮  。
2. 在删除窗口，点击  **确认**按钮以确认删除。

### 提供者 {#providers}

🌐 Providers

**路径:**  *用户与权限插件 > 提供者*

“用户与权限”功能允许启用和配置提供者，使终端用户可以通过第三方提供者登录，以通过 Strapi 应用 API 访问前端应用的内容。

🌐 The Users & Permissions feature allows enabling and configuring providers, for end users to log in via a third-party provider to access the content of a front-end application through the Strapi application API.

默认情况下，会提供一个提供者列表，其中包括“电子邮件”，它在启用用户和权限的所有 Strapi 应用中默认启用。

🌐 By default, a list of providers is available including one, "Email", enabled by default for all Strapi applications with Users & Permissions enabled.

1. 点击供应商的编辑  按钮以启用并配置。
2. 在提供者版本窗口中，点击*启用*选项的**TRUE**按钮。
3. 填写提供商的配置。每个提供商都有自己特定的配置集（请参阅[用户与权限提供商文档](/cms/configurations/users-and-permissions-providers#setting-up-the-provider---examples)）。
4. 点击 **保存** 按钮。

Strapi 默认未提供的其他服务提供商可以通过手动修改 Strapi 应用的代码来添加。点击以下任意卡片以获取有关配置或创建第三方服务提供商的更多信息：

🌐 Other providers that are not proposed by default by Strapi can be added manually through the code of your Strapi application. Click on any of the following cards to get additional information on configuring or creating third-party providers:

- [设置提供者](/cms/configurations/users-and-permissions-providers): 了解用户和权限提供者的工作原理，理解登录流程，并查看常见示例。
- [创建自定义提供程序](/cms/configurations/users-and-permissions-providers/new-provider-guide): 学习如何为“用户与权限”功能创建你自己的自定义提供程序。

:::note Username generation during provider registration

当终端用户通过认证提供者（如 Google 或 GitHub）注册时，Strapi 会自动使用提供者邮箱地址生成用户名，取 `@` 符号前的部分（例如，从 `joe@gmail.com` 中生成 `joe`）。

🌐 When an end user registers via an authentication provider (such as Google or GitHub), Strapi automatically generates a username from the provider email address, using the part before the `@` symbol (e.g., `joe` from `joe@gmail.com`).

如果生成的用户名已被占用，Strapi 会添加一个随机数字以使其唯一（例如，`joe1234`）。现有账户的用户名不会受到影响。

🌐 If the generated username is already taken, Strapi appends a random number to make it unique (e.g., `joe1234`). The existing account's username is not affected.

:::

### 电子邮件模板 {#email-templates}

🌐 Email templates

**路径：**  *用户与权限插件 > 邮件模板*

“用户与权限”功能使用两个电子邮件模板，“电子邮件地址确认”和“重置密码”，这些模板会发送给终端用户：

🌐 The Users & Permissions feature uses 2 email templates, "Email address confirmation" and "Reset password", that are sent to end users:

- 如果必须确认他们的账户才能激活，
- 如果他们需要重置 Strapi 账户的密码。

两个电子邮件模板都可以修改。

🌐 Both email templates can be modified.

1. 点击电子邮件模板的编辑  按钮进行配置和编辑。
2. 配置电子邮件模板：    | 设置名称       | 说明                                                                 |    |--------------- | ----------------------------------------------- |    | 发件人名称     | 指明电子邮件发件人的名称。                                                   |    | 发件人邮箱     | 指明电子邮件发件人的邮箱地址。                                                 |    | 回复邮箱       | （可选）指明用于接收终端用户回复邮件的邮箱地址。                                  |    | 主题           | 编写电子邮件的主题。可以使用变量（参见 [模板邮件](#templating-emails)）。             |
3. 编辑“消息”文本框中的电子邮件内容。电子邮件模板内容为 HTML 并使用变量（见 [模板化电子邮件](#templating-emails)）。
4. 点击 **完成** 按钮。

### 高级设置 {#advanced-settings}

🌐 Advanced settings

**路径：**  *用户与权限插件 > 高级设置*

与“用户与权限”功能相关的所有设置均在*高级设置*界面中进行管理，包括为终端用户选择默认角色、启用注册和电子邮件确认，以及选择重置密码的着陆页。

🌐 All settings related to the Users & Permissions feature are managed from the *Advanced Settings* interface, including the choice of a default role for end users, the enablement of sign-ups and email confirmation, as well as the choice of landing page for resetting a password.

1. Configure the settings of your choice, following the instructions below:    | Setting name  | Instructions         |    | ------------------------------------ | --------------------------------------------------------------|    | Default role for authenticated users | Click the drop-down list to choose the default role for new end users.                                                                                             |    | One account per email address        | Click on the **TRUE** button to limit to 1 the number of end-user accounts with the same email address.<br/>Click on **FALSE** to disable this limitation and allow several end-user accounts to be associated with the same email address (e.g. `kai.doe@strapi.io` can be used when logging in via several different providers).  |    | Enable sign-ups                      | Click on the **TRUE** button to enable end-user sign-ups.<br/>Click on **FALSE** to prevent end-user registration to your front-end application(s).                        |    | Reset password page                  | Indicate the URL of the reset password page for your front-end application(s).                                                                                     |    | Enable email confirmation            | Click on the **TRUE** button to enable end-user account confirmation by sending them a confirmation email.<br/>Click on **FALSE** to disable account confirmation.         |    | Redirection url                      | Indicate the URL of the page where end users should be redirected after confirming their Strapi account.                                                           |
2. 点击 **保存** 按钮。

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

🌐 Code-based configuration

虽然大多数用户和权限设置都是通过管理面板处理的，但可以通过配置和自定义 Strapi 项目的代码来微调一些更具体的设置。

🌐 While most of the Users & Permissions settings are handled via the admin panel, some more specific settings can be fine-tuned by configuring and customizing your Strapi project's code.

### JWT 配置 {#jwt-configuration}

🌐 JWT configuration

你可以通过使用[插件配置文件](/cms/configurations/plugins)来配置 JSON Web Token (JWT) 的生成。

🌐 You can configure the JSON Web Token (JWT) generation by using the [plugins configuration file](/cms/configurations/plugins).

Strapi 使用 [jsonwebtoken](https://www.npmjs.com/package/jsonwebtoken) 来生成 JWT。

#### JWT 管理模式 {#jwt-management-modes}

🌐 JWT management modes

用户和权限功能支持两种 JWT 管理模式。

🌐 The Users & Permissions feature supports 2 JWT management modes.

通过在 [`/config/plugins` 文件](/cms/configurations/plugins) 中设置 `users-permissions.config` 对象的 `jwtManagement` 属性来定义使用哪种模式。该属性可以接受 `legacy-support` 或 `refresh`：

🌐 Defining which mode is used is done by setting the `jwtManagement` property of the `users-permissions.config` object in the [`/config/plugins` file](/cms/configurations/plugins). The property accepts either `legacy-support` or `refresh`:

| 模式 | 描述 | 使用场景 |
|------|------|----------|
| `legacy-support` | （默认）使用传统配置签发长期有效的 JWT | 现有应用，简单身份验证 |
| `refresh` | 使用会话管理、短期访问令牌和刷新令牌以增强安全性 | 新应用，增强的安全性需求<br />（参见[管理面板配置](/cms/configurations/admin-panel#session-management)） |

为了向后兼容，用户与权限功能默认使用传统模式：

🌐 For backwards compatibility, the Users & Permissions feature defaults to legacy mode:

```js title="/config/plugins.js"
module.exports = ({ env }) => ({
  'users-permissions': {
    config: {
      jwtManagement: 'legacy-support',
      jwt: {
        expiresIn: '30d', // Traditional JWT expiry
      },
    },
  },
});
```

:::note Notes

- `jwtSecret` 是用于创建新的 JWT 的随机字符串，通常通过 `JWT_SECRET` [环境变量](/cms/configurations/environment#strapi) 设置。
- `jwt.expiresIn`（仅限旧模式）以秒为单位表示，或者以描述时间跨度的字符串表示。<br/>  例如：60, "45m", "10h", "2 days", "7d", "2y"。数值会被解释为秒数。如果使用字符串，请确保提供时间单位（分钟、小时、天、年等），否则默认使用毫秒单位（"120" 等于 "120ms"）。

:::

:::warning

出于安全考虑，不建议将 JWT 过期时间设置为超过 30 天。

🌐 Setting JWT expiry for more than 30 days is not recommended due to security concerns.

:::

当使用 `refresh` 模式时，配置文件如下所示：

🌐 When the `refresh` mode is used, the configuration file looks like the following:

```js title="/config/plugins.js"

module.exports = ({ env }) => ({
  // …
  'users-permissions': {
    config: {
      jwtManagement: 'refresh',
      sessions: {
        accessTokenLifespan: 600, // 10 minutes (default)
        maxRefreshTokenLifespan: 2592000, // 30 days (default)
        idleRefreshTokenLifespan: 1209600, // 14 days (default)
        maxSessionLifespan: 86400, // 1 day (default)
        idleSessionLifespan: 7200, // 2 hours (default)
        httpOnly: false, // Set to true for HTTP-only cookies
        cookie: {
          name: 'strapi_up_refresh',
          sameSite: 'lax',
          path: '/',
          secure: false, // true in production
        },
      },
    },
  },
  // ...
});
```

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

  // …
  'users-permissions': {
    config: {
      jwtManagement: 'refresh',
      sessions: {
        accessTokenLifespan: 600, // 10 minutes (default)
        maxRefreshTokenLifespan: 2592000, // 30 days (default)
        idleRefreshTokenLifespan: 1209600, // 14 days (default)
        maxSessionLifespan: 86400, // 1 day (default)
        idleSessionLifespan: 7200, // 2 hours (default)
        httpOnly: false, // Set to true for HTTP-only cookies
        cookie: {
          name: 'strapi_up_refresh',
          sameSite: 'lax',
          path: '/',
          secure: false, // true in production
        },
      },
    },
  },
  // ...
});
```

### 注册配置 {#registration-configuration}

🌐 Registration configuration

如果你在你的用户 **模型** Models 中添加了任何额外字段，Models 在 Strapi 中也称为内容类型，用于定义内容结构的表示。<br/>用户是任何新的 Strapi 应用中都会出现的一种特殊内置内容类型。你可以自定义用户模型，例如添加更多字段，就像其他模型一样。<br/>更多信息，请参考 [models](/cms/backend-customization/models) 文档。 需要在注册时被接受的字段，你需要将它们添加到 [the `/config/plugins` file](/cms/configurations/plugins) 中 `config.register` 对象的允许字段列表，否则它们将不会被接受。

以下示例展示了如何确保在用户注册时 API 接受名为“nickname”的字段：

🌐 The following example shows how to ensure a field called "nickname" is accepted by the API on user registration:

```js title="/config/plugins.js"
module.exports = ({ env }) => ({
  // ...
  "users-permissions": {
    config: {
      register: {
        allowedFields: ["nickname"],
      },
    },
  },
  // ...
});
```

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

  // ...
  "users-permissions": {
    config: {
      register: {
        allowedFields: ["nickname"],
      },
    },
  },
  // ...
});
```

### 速率限制配置 {#rate-limiting-configuration}

🌐 Rate limiting configuration

对身份验证和注册端点应用了速率限制以防止滥用。可以配置以下参数以更改其行为。 [koa2-ratelimit](https://github.com/ysocorp/koa2-ratelimit?tab=readme-ov-file#configuration) 包提供了其他配置选项：

以下选项可在 [the `/config/plugins` 文件](/cms/configurations/plugins) 中使用：

🌐 The following options are available in [the `/config/plugins` file](/cms/configurations/plugins):

| 参数 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| `ratelimit` | 自定义身份验证和注册端点速率限制的设置 | 对象 | `{}` |
| `ratelimit.enabled` | 启用或禁用速率限制器 | 布尔值 | `true` |
| `ratelimit.interval` | 被视为同一速率限制桶的请求时间窗口（毫秒） | 整数 | `60000`（1 分钟） |
| `ratelimit.max` | 时间窗口内允许的最大请求数 | 整数 | `10` |
| `ratelimit.prefixKey` | 速率限制键的前缀 | 字符串 | `${userIdentifier}:${requestPath}:${ctx.request.ip}` |

```js title="/config/plugins.js"
module.exports = ({ env }) => ({
  // ... other plugins configuration ...
  // Users & Permissions configuration
  'users-permissions': {
    config: {
      ratelimit: {
        enabled: true,
        interval: 60000, // 1 minute
        max: 10,
      },
    },
  },
  // ...
});
```

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

  // ... other plugins configuration ...
  // Users & Permissions configuration
  'users-permissions': {
    config: {
      ratelimit: {
        enabled: true,
        interval: 60000, // 1 minute
        max: 10,
      },
    },
  },
  // ...
});
```

### 电子邮件模板配置 {#templating-emails}

🌐 Email template configuration 

默认情况下，这个插件附带两个模板：重置密码和邮箱地址确认。模板使用 [Lodash 的 `template()` 方法](https://lodash.nodejs.cn/docs/4.17.15#template) 来填充变量。

🌐 By default this plugin comes with two templates: reset password and email address confirmation. The templates use [Lodash](https://lodash.nodejs.cn/docs/4.17.15#template) to populate the variables.

你可以在管理员面板的 **插件** > **角色与权限** > **电子邮件模板** 标签下更新这些模板（参见 [配置电子邮件模板](#email-templates)）。

🌐 You can update these templates under **Plugins** > **Roles & Permissions** > **Email Templates** tab in the admin panel (see [configuring email templates](#email-templates)).

可以使用以下变量：

🌐 The following variables can be used:

<br/>

- `USER`（对象）
  - `username`
  - `email`
- `TOKEN` 对应于生成的用于重置密码的令牌。
- `URL` 是用户在点击电子邮件中的链接后将被重定向到的链接。
- `SERVER_URL` 是绝对服务器 URL（在服务器配置中设置）。

<br/>

- `USER`（对象）
  - `username`
  - `email`
- `CODE` 对应生成的代码，用于确认用户的电子邮件。
- `URL` 是确认代码的 Strapi 后端 URL（默认是 `/auth/email-confirmation`）。
- `SERVER_URL` 是绝对服务器 URL（在服务器配置中设置）。

### 安全配置 {#security-configuration}

🌐 Security configuration

JWT 可以被验证和信任，因为信息是经过数字签名的。要签署一个令牌，需要一个_密钥_。默认情况下，Strapi 将其存储为 `.env` 文件中的 `JWT_SECRET` 环境变量。

🌐 JWTs can be verified and trusted because the information is digitally signed. To sign a token, a _secret_ is required. By default, Strapi stores it as the `JWT_SECRET` environment variable in the `.env` file.

如果你想使用不同的环境变量，可以更新配置文件。

🌐 If you want to use a different environment variable, you can update the configuration file.

```js title="/src/extensions/users-permissions/config/jwt.js"

module.exports = {
  jwtSecret: process.env.SOME_ENV_VAR,
};
```

```ts title="/src/extensions/users-permissions/config/jwt.ts"

  jwtSecret: process.env.SOME_ENV_VAR,
};
```

#### 创建自定义回调验证器 {#creating-a-custom-password-validation}

🌐 Creating a custom callback validator 

默认情况下，Strapi SSO 仅重定向到与配置中的 URL 完全相等的重定向 URL：

🌐 By default, Strapi SSO only redirects to the redirect URL that is exactly equal to the url in the configuration:

如果你需要配置自定义处理程序以接受其他 URL，你可以在你的 `plugins.js` 中为 `users-permissions` 插件创建一个回调 `validate` 函数。

🌐 If you need to configure a custom handler to accept other URLs, you can create a callback `validate` function in your `plugins.js` for the `users-permissions` plugin.

```tsx title="/config/plugins.js|ts"
  // ... other plugins configuration ...
  // Users & Permissions configuration
  'users-permissions': {
    enabled: true,
    config: {
      callback: {
        validate: (cbUrl, options) => {
          // cbUrl is where Strapi is being asked to redirect the auth info
          // that was received from the provider to

          // in this case, we will only validate that the 
          // if using a base url, you should always include the trailing slash
          // although in real-world usage you should also include the full paths
          if (cbUrl.startsWith('https://myproxy.mysite.com/') || 
              cbUrl.startsWith('https://mysite.com/')) {
            return;
          }

          // Note that you MUST throw an error to fail validation
          // return values are not checked
          throw new Error('Invalid callback url');
        },
      },
    },
  },
```

### 路由和策略自定义 {#customizing-routes-and-policies}

🌐 Route and policy customization 

用户与权限功能的路由和控制器可以通过 [插件扩展系统](/cms/plugins-development/plugins-extension) 进行扩展和覆盖。这对于向用户端点添加自定义策略、覆盖控制器逻辑或添加新路由非常有用。

🌐 The Users & Permissions feature routes and controllers can be extended and overridden through the [plugin extension system](/cms/plugins-development/plugins-extension). This is useful for adding custom policies to user endpoints, overriding controller logic, or adding new routes.

- [自定义用户与权限插件路由](/cms/backend-customization/guides/customizing-users-permissions-plugin-routes): 添加自定义策略、覆盖控制器，并向用户集合添加新路由。

## 使用 {#usage}

🌐 Usage

用户和权限功能既可以通过管理面板使用，也可以通过 API 使用，以创建新的终端用户账户。

🌐 The Users & Permissions feature can be used both via the admin panel, to create new end-user accounts, and via the APIs.

### 管理员面板使用 {#admin-panel-usage}

🌐 Admin panel usage

**使用此功能的路径:**  内容管理器

通过“用户与权限”功能，终端用户及其账户信息被作为一种内容类型进行管理。当“用户与权限”安装在 Strapi 应用上时，会自动创建 3 种集合类型，其中包括“用户”，这是唯一可以直接在内容管理器中使用的类型。

🌐 With the Users & Permissions feature, the end users and their account information are managed as a content-type. When Users & Permissions is installed on a Strapi application, 3 collection types are automatically created, including "User" which is the only one available directly in the Content Manager.

在前端应用中使用“用户与权限”功能注册新终端用户，包括向用户集合类型添加新条目。

🌐 Registering new end users in a front-end application with the Users & Permissions feature consists of adding a new entry to the User collection type.

1. 在  内容管理器中，转到用户集合类型。
2. 点击右上角的**创建新条目**按钮。
3. 填写条目的默认字段。管理员为你的 Strapi 应用专门添加的附加字段也可能会显示。

| 字段       | 说明                                                                 | 
|-----------|--------------------------------------------------------------------|
| 用户名     | 填写终端用户的用户名。                                                |
| 电子邮件   | 在文本框中填写终端用户的完整电子邮件地址。                               |
| 密码       | （可选）在文本框中输入新密码。你可以点击  图标以显示密码。                |
| 已确认     | （可选）点击 **开启** 以确认终端用户账户。                                  |
| 已封锁     | （可选）点击 **开启** 以封锁终端用户账户，防止其访问内容。                 |
| 角色       | （可选）指明应授予新终端用户的角色。如果未填写此字段，终端用户将被分配为默认角色（请参见[高级设置](#advanced-settings)中的 "默认角色" 选项）。 |
4. 点击 **保存** 按钮。

:::note

如果终端用户可以在你的前端应用上自行注册（请参阅[高级设置](#advanced-settings)中的“启用注册”选项），将自动创建一个新条目，并且该条目的字段将填充终端用户提供的信息。然而，Strapi 应用的管理员可以编辑所有字段。

🌐 If end users can register themselves on your front-end application (see "Enable signups" option in [advanced settings](#advanced-settings)), a new entry will automatically be created and the fields of that entry will be populated with the information indicated by the end user. All fields can however be edited by an administrator of the Strapi application.

:::

### API 使用 {#api-usage}

🌐 API usage

每当发送 API 请求时，服务器会检查是否存在 `Authorization` 头，并验证发出请求的用户是否有权访问该资源。

🌐 Each time an API request is sent the server checks if an `Authorization` header is present and verifies if the user making the request has access to the resource.

:::note

当你创建一个没有角色的用户，或者如果你使用 `/api/auth/local/register` 路由，`authenticated` 角色将被赋予该用户。

🌐 When you create a user without a role, or if you use the `/api/auth/local/register` route, the `authenticated` role is given to the user.

:::

“用户与权限”功能通过 REST API 和 GraphQL API 提供身份验证、用户管理以及角色/权限的端点。完整的端点参考以及请求和响应示例可在专门的子页面上查看：

🌐 The Users & Permissions feature exposes authentication, user management, and role/permission endpoints through both the REST API and the GraphQL API. Full endpoint references with request and response examples are available on the dedicated sub-pages:

- [REST API](/cms/features/users-permissions/rest-api): 用于用户与权限功能的身份验证端点、用户增删改查、角色和权限。
- [GraphQL API](/cms/features/users-permissions/graphql-api): 通过 GraphQL 进行身份验证变更、用户查询和角色管理。

### 令牌使用 {#token-usage}

🌐 Token usage

登录或注册时收到的 `jwt` 可以随后用于执行权限受限的 API 请求。要以用户身份发起 API 请求，请使用 Bearer 令牌模式将 JWT 放入请求的 `Authorization` 头中：

🌐 The `jwt` received when logging in or registering may then be used for making permission-restricted API requests. To make an API request as a user, place the JWT into an `Authorization` header of the request using the Bearer token pattern:

```js

const token = 'YOUR_TOKEN_HERE';

// Request API.
axios
  .get('http://localhost:1337/api/posts', {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  })
  .then(response => {
    // Handle success.
    console.log('Data: ', response.data);
  })
  .catch(error => {
    // Handle error.
    console.log('An error occurred:', error.response);
  });
```

任何没有令牌的请求默认将假定 `public` 角色权限。在管理面板中修改每个用户角色的权限。身份验证失败会返回 `401 (unauthorized)` 错误。

🌐 Any request without a token will assume the `public` role permissions by default. Modify the permissions of each user's role in the admin panel. Authentication failures return a `401 (unauthorized)` error.

### Strapi 上下文中的用户对象 {#user-object-in-strapi-context}

🌐 User object in Strapi context

`user` 对象可供成功认证的请求使用。

🌐 The `user` object is available to successfully authenticated requests.

经过身份验证的 `user` 对象是 `ctx.state` 的一个属性，如以下示例所示：

🌐 The authenticated `user` object is a property of `ctx.state`, as shown in the following example:

```js
create: async ctx => {
  const { id } = ctx.state.user;

  const depositObj = {
    ...ctx.request.body,
    depositor: id,
  };

  const data = await strapi.services.deposit.add(depositObj);

  // Send 201 `created`
  ctx.created(data);
};
```
