Skip to main content

用户和权限

¥Users & Permissions

用户和权限功能允许管理终端用户

¥The Users & Permissions feature allows the management of the end-users

Strapi 项目的。它提供基于 JSON Web Tokens (JWT) 的完整身份验证过程来保护你的 API,以及访问控制列表 (ACL) 策略,使你能够管理用户组之间的权限。

¥of a Strapi project. It provides a full authentication process based on JSON Web Tokens (JWT) to protect your API, and an access-control list (ACL) strategy that enables you to manage permissions between groups of users.

功能的身份证

计划:免费功能。
角色和权限:角色 > 插件中的 CRUD 权限 - 用户和权限。 ​​
激活:默认可用。
环境:在开发和生产环境中均可用。

¥ Plan: Free feature.
Role & permission: CRUD permissions in Roles > Plugins - Users & Permissions.
Activation: Available by default.
Environment: Available in both Development & Production environment.

管理面板配置

¥Admin panel configuration

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

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

角色

¥Roles

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

¥The Users & Permissions feature allows to create and manage roles for end users, to configure what they can have access to.

创建新角色

¥Creating a new role

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

¥Path: Users & Permissions plugin > Roles

在角色界面的右上角,显示一个添加新角色按钮。它允许为 Strapi 应用的终端用户创建新角色。

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

单击添加新角色按钮以重定向到角色编辑界面,你可以在其中命名新角色并定义其详细信息和权限(参见 编辑角色)。

¥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).

End-users roles interfaceEnd-users roles interface
注意

默认情况下归属于所有新终端用户的终端用户角色可以在用户和权限插件的高级设置子部分中定义(请参阅 高级设置)。

¥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).

编辑角色

¥Editing a role

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

¥Path: Users & Permissions plugin > 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:

  • 已验证:仅当终端用户登录到前端应用时才能访问内容。

    ¥Authenticated: for end users to access content only if they are logged in to a front-end application.

  • 民众:供终端用户无需登录前端应用即可访问内容。

    ¥Public: for end users to access content without being logged in to a front-end application.

但是可以创建更多角色(参见 创建新角色),并且所有角色都可以通过角色编辑界面进行编辑。

¥More roles can however be created (see Creating a new role), and all can be edited through the role edition interface.

  1. 单击要编辑的角色的编辑按钮 — 除非你直接从创建新角色进入角色编辑界面。

    ¥Click on the edit button of the role to edit — except if you directly landed on the role edition interface from creating a new role.

  2. 按照下表中的说明填写角色详细信息:

    ¥Fill in the Role details, following the instructions from the table below:

角色详情指示
名称在文本框中写入角色的新名称。
描述在文本框中写下角色的描述。它应该帮助管理员了解角色授予访问权限的内容。
  1. 通过以下方式配置终端用户角色的权限:

    ¥Configure the end-user role's Permissions by:

    1. 单击要配置的权限类别的名称(例如应用、内容管理器、电子邮件等)。

      ¥Clicking on the name of the permission category to configure (e.g. Application, Content-Manager, Email etc.).

    2. 勾选要授予角色的操作和权限的框。

      ¥Ticking the boxes of the actions and permissions to grant for the role.

  2. 单击“保存”按钮。

    ¥Click on the Save button.

提示

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

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

Configuring a role for end usersConfiguring a role for end users

删除角色

¥Deleting a role

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

¥Path: Users & Permissions plugin > Roles

尽管无法删除 2 个默认终端用户角色,但其他角色可以删除,只要没有终端用户仍将此角色归属于其账户即可。

¥Although the 2 default end-user roles cannot be deleted, the other ones can, as long as no end user still has this role attributed to their account.

  1. 点击角色记录右侧的删除按钮

    ¥Click on the delete button on the right side of the role's record.

  2. 在删除窗口中,单击 确认按钮以确认删除。

    ¥In the deletion window, click on the Confirm button to confirm the deletion.

提供者

¥Providers

路径: 用户和权限插件 > 提供商

¥Path: Users & Permissions plugin > Providers

用户和权限功能允许启用和配置提供商,以便终端用户通过第三方提供商登录,通过 Strapi 应用 API 访问前端应用的内容。

¥The Users & Permissions feature allows enabling and configuring providers, for end users to login 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. 点击提供商的编辑 按钮进行启用和配置。

    ¥Click on the edit button of the provider to enable and configure.

  2. 在提供商版本窗口中,单击启用选项的 TRUE 按钮。

    ¥In the provider edition window, click on the TRUE button of the Enable option.

  3. 填写提供商的配置。每个提供商都有自己特定的配置集(参见 用户和权限提供商文档)。

    ¥Fill in the provider's configurations. Each provider has its own specific set of configurations (see Users & Permissions providers documentation).

  4. 单击“保存”按钮。

    ¥Click on the Save button.

Providers interfaceProviders interface
提示

Strapi 默认情况下未建议的其他提供者可以通过 Strapi 应用的代码手动添加(请参阅 专用指南)。

¥Other providers that are not proposed by default by Strapi can be added manually through the code of your Strapi application (see the dedicated guide).

电子邮件模板

¥Email templates

路径: 用户和权限插件 > 电子邮件模板

¥Path: Users & Permissions plugin > Email templates

用户和权限功能使用 2 个电子邮件模板 "电子邮件地址确认" 和 "重设密码",发送给终端用户:

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

  • 如果必须确认他们的账户才能激活,

    ¥if their account must be confirmed to be activated,

  • 如果他们需要重置 Strapi 账户的密码。

    ¥if they need to reset the password of their Strapi account.

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

¥Both email templates can be modified.

  1. 点击电子邮件模板的编辑 按钮进行配置和编辑。

    ¥Click on the edit button of the email template to configure and edit.

  2. 配置电子邮件模板:

    ¥Configure the email template:

    设置名称指示
    发货人名称注明电子邮件发送者的名称。
    发送者电子邮件注明电子邮件发送者的电子邮件地址。
    响应电子邮件(可选)指示终端用户的响应电子邮件将发送到的电子邮件地址。
    主题写下电子邮件的主题。可以使用变量(参见 模板电子邮件)。
  3. 在 "信息" 文本框中编辑电子邮件的内容。电子邮件模板内容采用 HTML 格式并使用变量(请参阅 模板电子邮件)。

    ¥Edit the content of the email in the "Message" textbox. Email templates content is in HTML and uses variables (see templating emails).

  4. 单击完成按钮。

    ¥Click on the Finish button.

Email templates interfaceEmail templates interface

高级设置

¥Advanced Settings

路径: 用户和权限插件 > 高级设置

¥Path: Users & Permissions plugin > 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:

    设置名称指示
    经过身份验证的用户的默认角色单击下拉列表为新终端用户选择默认角色。
    每个电子邮件地址一个账户点击 TRUE 按钮可将具有相同电子邮件地址的终端用户账户数量限制为 1。
    点击 FALSE 可禁用此限制,并允许多个终端用户账户与同一个电子邮件地址相关联(例如,当通过多个不同的提供商登录时,可以使用 kai.doe@strapi.io)。
    启用注册单击“TRUE”按钮以启用终端用户注册。
    单击“FALSE”以阻止终端用户注册到你的前端应用。
    重置密码页面指示前端应用的重置密码页面的 URL。
    启用电子邮件确认单击“TRUE”按钮,通过向终端用户发送确认电子邮件来启用账户确认。
    单击“FALSE”以禁用账户确认。
    重定向网址指示终端用户在确认其 Strapi 账户后应重定向到的页面 URL。
  2. 单击“保存”按钮。

    ¥Click the Save button.

Advanced settings interfaceAdvanced settings interface

基于代码的配置

¥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

你可以使用 插件配置文件.config 配置 JWT 生成。

¥You can configure the JWT generation by using the plugins configuration file.

Strapi 使用 jsonwebtoken  生成 JWT。

¥Strapi uses jsonwebtoken  to generate the JWT.

可用选项:

¥Available options:

  • jwtSecret:用于创建新 JWT 的随机字符串,通常使用 JWT_SECRET 环境变量 设置。

    ¥jwtSecret: random string used to create new JWTs, typically set using the JWT_SECRET environment variable.

  • jwt.expiresIn:以秒或描述时间跨度的字符串表示。
    例如:60、"45m"、"10 小时"、"2 天"、"7 天"、"2 年"。数值被解释为秒数。如果你使用字符串,请确保提供时间单位(分钟、小时、天、年等),否则默认使用毫秒单位("120" 等于 "120ms")。

    ¥jwt.expiresIn: expressed in seconds or a string describing a time span.
    Eg: 60, "45m", "10h", "2 days", "7d", "2y". A numeric value is interpreted as a seconds count. If you use a string be sure you provide the time units (minutes, hours, days, years, etc), otherwise milliseconds unit is used by default ("120" is equal to "120ms").

/config/plugins.js

module.exports = ({ env }) => ({
// ...
'users-permissions': {
config: {
jwt: {
expiresIn: '7d',
},
},
},
// ...
});
警告

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

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

注册配置

¥Registration configuration

如果你在用户模型中添加了任何其他字段

¥If you have added any additional fields in your User model

需要在注册时接受,你需要将它们添加到 /config/plugins 文件config.register 对象中允许的字段列表中,否则将不被接受。

¥that need to be accepted on registration, you need to added them to the list of allowed fields in the config.register object of the /config/plugins file, otherwise they will not be accepted.

以下示例显示如何确保 API 在用户注册时接受名为 "nickname" 的字段:

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

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

模板化电子邮件

¥Templating emails

默认情况下,该插件附带两个模板:重置密码和电子邮件地址确认。模板使用 Lodash 的 `template()` 方法  填充变量。

¥By default this plugin comes with two templates: reset password and email address confirmation. The templates use Lodash's `template()` method  to populate the variables.

你可以在管理面板中的插件 > 角色和权限 > 电子邮件模板选项卡下更新这些模板(参见 配置电子邮件模板)。

¥You can update these templates under Plugins > Roles & Permissions > Email Templates tab in the admin panel (see configuring email templates).

可以使用以下变量:

¥The following variables can be used:


  • USER (object)
    • username
    • email
  • TOKEN corresponds to the token generated to be able to reset the password.
  • URL is the link where the user will be redirected after clicking on it in the email.
  • SERVER_URL is the absolute server url (configured in server configuration).

安全配置

¥Security configuration

JWT 可以被验证和信任,因为信息是经过数字签名的。要签署令牌,需要一个秘密。默认情况下,Strapi 生成并将其存储在 /extensions/users-permissions/config/jwt.js 中。

¥JWTs can be verified and trusted because the information is digitally signed. To sign a token a secret is required. By default Strapi generates and stores it in /extensions/users-permissions/config/jwt.js.

这在开发期间很有用,但出于安全原因,建议在部署到生产时通过环境变量 JWT_SECRET 设置自定义令牌。

¥This is useful during development but for security reasons it is recommended to set a custom token via an environment variable JWT_SECRET when deploying to production.

默认情况下,你可以设置 JWT_SECRET 环境变量,它将用作秘密。如果你想使用其他变量,你可以更新配置文件。

¥By default you can set a JWT_SECRET environment variable and it will be used as secret. If you want to use another variable you can update the configuration file.

/extensions/users-permissions/config/jwt.js

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

创建自定义回调验证器

¥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:

Users & Permissions configurationUsers & Permissions 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.

/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');
},
},
},
},

用法

¥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

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

¥Path to use the feature: Content Manager

使用用户和权限功能,终端用户及其账户信息将作为内容类型进行管理。在 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.

Managing end users via the Content ManagerManaging end users via the Content Manager

使用用户和权限插件在前端应用中注册新的终端用户包括向用户集合类型添加新条目。

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

  1. 转到 内容管理器中的用户集合类型。

    ¥Go to the User collection type in the Content Manager.

  2. 单击右上角的“创建新条目”按钮。

    ¥Click on the Create new entry button in the top right corner.

  3. 填写条目的默认字段。管理员专门为你的 Strapi 应用添加的其他字段也可能会显示。

    ¥Fill in the default fields of the entry. Additional fields added specifically for your Strapi application by your administrators may be displayed as well.

    字段指示
    用户名写入终端用户的用户名。
    电子邮件在文本框中填写终端用户的完整电子邮件地址。
    密码(可选)在文本框中写入新密码。你可以单击 图标以显示密码。
    已确认(可选)单击“开”确认终端用户账户。
    已阻止(可选)单击“开”阻止终端用户的账户,以阻止他们访问内容。
    角色(可选)指示应授予新终端用户的角色。如果未填写此字段,则终端用户将被归为默认角色(请参阅 高级设置 中的 "默认角色" 选项)。
  4. 单击“保存”按钮。

    ¥Click on the Save button.

注意

如果终端用户可以在你的前端应用上注册自己(请参阅 高级设置 中的 "启用注册" 选项),则会自动创建一个新条目,并且该条目的字段将填充终端用户指示的信息。不过,所有字段都可以由 Strapi 应用的管理员进行编辑。

¥If end users can register themselves on your front-end application (see "Enable signups" option in advanced settings), a new entry will automatically be created and the fields of that entry will be filled up 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 请求时,服务器都会检查 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.

注意

当你创建没有角色的用户时,或者如果你使用 /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.

标识符

¥Identifier

identifier 参数可以是电子邮件或用户名,如以下示例所示:

¥The identifier param can be an email or username, as in the following examples:

import axios from 'axios';

// Request API.
axios
.post('http://localhost:1337/api/auth/local', {
identifier: 'user@strapi.io',
password: 'strapiPassword',
})
.then(response => {
// Handle success.
console.log('Well done!');
console.log('User profile', response.data.user);
console.log('User token', response.data.jwt);
})
.catch(error => {
// Handle error.
console.log('An error occurred:', error.response);
});

令牌使用

¥Token usage

然后,jwt 可用于发出权限受限的 API 请求。要以用户身份发出 API 请求,请将 JWT 放入 GET 请求的 Authorization 标头中。

¥The jwt 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 GET request.

默认情况下,任何没有令牌的请求都将采用 public 角色权限。在管理仪表板中修改每个用户角色的权限。

¥Any request without a token will assume the public role permissions by default. Modify the permissions of each user's role in the admin dashboard.

身份验证失败会返回 401 (unauthorized) 错误。

¥Authentication failures return a 401 (unauthorized) error.

token 变量是登录或注册时收到的 data.jwt

¥The token variable is the data.jwt received when logging in or registering.

import axios from 'axios';



const token = 'YOUR_TOKEN_HERE';



// Request API.
axios
.get('http://localhost:1337/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);
});

用户注册

¥User registration

可以像以下示例一样在数据库中创建一个默认角色为 'registered' 的新用户:

¥Creating a new user in the database with a default role as 'registered' can be done like in the following example:

import axios from 'axios';

// Request API.
// Add your own code here to customize or restrict how the public can register new users.
axios
.post('http://localhost:1337/api/auth/local/register', {
username: 'Strapi user',
email: 'user@strapi.io',
password: 'strapiPassword',
})
.then(response => {
// Handle success.
console.log('Well done!');
console.log('User profile', response.data.user);
console.log('User token', response.data.jwt);
})
.catch(error => {
// Handle error.
console.log('An error occurred:', error.response);
});

Strapi 上下文中的用户对象

¥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.

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);
};