Skip to main content

用户和权限插件

¥Users & Permissions plugin

用户和权限插件提供了基于 JSON Web 令牌 (JWT) 的完整身份验证过程来保护你的 API,以及访问控制列表 (ACL) 策略,使你能够管理用户组之间的权限。用户和权限插件是默认安装的,无法卸载。

¥The Users & Permissions plugin 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. The Users & Permissions plugin is installed by default and can not be uninstalled.

用户指南描述了如何从管理面板使用 用户和权限插件。本页面更多地介绍了使用用户和权限插件的开发者相关方面。

¥The user guide describes how to use the Users & Permissions plugin from the admin panel. The present page is more about the developer-related aspects of using the Users & Permissions plugin.

概念

¥Concept

用户和权限插件为你的应用添加了一个访问层。该插件使用 JWTs 来验证用户身份。你的 JWT 包含你的用户 ID,该 ID 与你的用户所在的组相匹配,并用于确定是否允许访问该路由。

¥The Users & Permissions plugin adds an access layer to your application. The plugin uses JWTs to authenticate users. Your JWT contains your user ID, which is matched to the group your user is in and used to determine whether to allow access to the route.

每次发送 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.

管理角色权限

¥Manage role permissions

公共角色

¥Public role

这是服务器收到没有 Authorization 标头的请求时使用的默认角色。任何人都可以访问授予此角色的任何权限(即可访问端点)。

¥This is the default role used when the server receives a request without an Authorization header. Any permissions (i.e. accessible endpoints) granted to this role will be accessible by anyone.

当你希望前端应用无需用户身份验证和授权即可访问所有内容时,通常的做法是选择 find / findOne 端点。

¥It is common practice to select find / findOne endpoints when you want your front-end application to access all the content without requiring user authentication and authorization.

已验证的角色

¥Authenticated role

如果未提供角色,这是在创建时授予每个新用户的默认角色。在此角色中,你定义用户可以访问的路由。

¥This is the default role that is given to every new user at creation if no role is provided. In this role you define routes that a user can access.

权限管理

¥Permissions management

通过单击角色名称,你可以查看应用中可用的所有功能(这些功能与显示的特定路由相关)。

¥By clicking on the Role name, you can see all functions available in your application (with these functions related to the specific route displayed).

如果你检查函数名称,它会使你正在编辑的当前角色可以访问该路由。在右侧边栏你可以看到与该功能相关的 URL。

¥If you check a function name, it makes this route accessible by the current role you are editing. On the right sidebar you can see the URL related to this function.

更新默认角色

¥Update the default role

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

要更改默认角色,请转到 Advanced settings 选项卡并更新 Default role for authenticated users 选项。

¥To change the default role, go to the Advanced settings tab and update the Default role for authenticated users option.

验证

¥Authentication

登录

¥Login

提交用户的标识符和密码凭据以进行身份验证。身份验证成功后,响应数据将包含用户信息以及身份验证令牌。

¥Submit the user's identifier and password credentials for authentication. On successful authentication the response data will have the user's information along with an authentication token.

本地的

¥Local

identifier 参数可以是电子邮件或用户名。

¥The identifier param can be an email or username.

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.

用法

¥Usage

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

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 年"。数值被解释为秒数。如果你需要更高级的示例,请参阅 ms 包

    ¥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 need more advanced examples please see the ms package.

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

如果你在用户模型中添加了注册时需要接受的任何其他字段,则需要将它们添加到 register 配置选项中的允许字段列表中,否则它们将不会被接受。

¥If you have added any additional fields to your user model that need to be accepted on registration, they need to be added to the list of allowed fields in the register configuration option, otherwise they will not be accepted.

例如,如果你添加了一个名为 "nickname" 的字段,你希望在用户注册时从 API 接受该字段:

¥For example, if you have added a field called "nickname" that you wish to accept from the API on user registration:

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

用法

¥Usage

在数据库中创建一个新用户,默认角色为 'registered'。

¥Creates a new user in the database with a default role as 'registered'.

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

提供者

¥Providers

授予最纯粹 允许你使用 OAuth 和 OAuth2 提供程序在应用中启用身份验证。

¥Grant and Purest allow you to use OAuth and OAuth2 providers to enable authentication in your application.

为了更好地理解,请查看以下登录流程的描述。示例使用 github 作为提供程序,但对于其他提供程序也一样。

¥For a better understanding, review the following description of the login flow. The example uses github as the provider but it works the same for other providers.

了解登录流程

¥Understanding the login flow

这么说吧:

¥Let's say that:

  • Strapi 的后端位于:strapi.website.com,和

    ¥Strapi's backend is located at: strapi.website.com, and

  • 你的应用前端位于:website.com

    ¥Your app frontend is located at: website.com

  1. 用户进入你的前端应用 (https://website.com) 并单击你的按钮 connect with Github

    ¥The user goes on your frontend app (https://website.com) and clicks on your button connect with Github.

  2. 前端将选项卡重定向到后端 URL:https://strapi.website.com/api/connect/github

    ¥The frontend redirects the tab to the backend URL: https://strapi.website.com/api/connect/github.

  3. 后端将选项卡重定向到用户登录的 GitHub 登录页面。

    ¥The backend redirects the tab to the GitHub login page where the user logs in.

  4. 完成后,Github 会将选项卡重定向到后端 URL:https://strapi.website.com/api/connect/github/callback?code=abcdef

    ¥Once done, Github redirects the tab to the backend URL:https://strapi.website.com/api/connect/github/callback?code=abcdef.

  5. 后端使用给定的 code 从 Github 获取 access_token,该 access_token 可用于在一段时间内向 Github 发出授权请求以获取用户信息。

    ¥The backend uses the given code to get an access_token from Github that can be used for a period of time to make authorized requests to Github to get the user info.

  6. 然后,后端使用参数 access_token 将选项卡重定向到你选择的 URL(例如:http://website.com/connect/github/redirect?access_token=eyfvg)。

    ¥Then, the backend redirects the tab to the url of your choice with the param access_token (example: http://website.com/connect/github/redirect?access_token=eyfvg).

  7. 前端 (http://website.com/connect/github/redirect) 使用 https://strapi.website.com/api/auth/github/callback?access_token=eyfvg 调用后端,后端返回 Strapi 用户配置文件及其 jwt
    (在后台,后端向 Github 请求用户的个人资料,并在 Github 用户的电子邮件地址和 Strapi 用户的电子邮件地址上进行匹配)。

    ¥The frontend (http://website.com/connect/github/redirect) calls the backend with https://strapi.website.com/api/auth/github/callback?access_token=eyfvg that returns the Strapi user profile with its jwt.
    (Under the hood, the backend asks Github for the user's profile and a match is done on Github user's email address and Strapi user's email address).

  8. 前端现在拥有用户的 jwt,这意味着用户已连接,前端可以向后端发出经过身份验证的请求!

    ¥The frontend now possesses the user's jwt, which means the user is connected and the frontend can make authenticated requests to the backend!

可以在此处找到处理此流程的前端应用的示例:React 登录示例应用

¥An example of a frontend app that handles this flow can be found here: react login example app.

设置服务器 URL

¥Setting up the server url

在设置提供者之前,你必须在 server.js 中指定后端的绝对 URL。

¥Before setting up a provider you must specify the absolute url of your backend in server.js.

example - config/server.js

config/server.js

module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
url: env('', 'http://localhost:1337'),
});
💡 提示

稍后你将将此 URL 提供给你的提供者。
对于开发,一些提供商接受使用 localhost url,但许多提供商不接受。在这种情况下,我们建议使用 ngrok (ngrok http 1337),它将创建从它创建的 url 到本地主机 url 的代理隧道(例如:url: env('', 'https://5299e8514242.ngrok.io'),)。

¥Later you will give this url to your provider.
For development, some providers accept the use of localhost urls but many don't. In this case we recommend to use ngrok (ngrok http 1337) that will make a proxy tunnel from a url it created to your localhost url (ex: url: env('', 'https://5299e8514242.ngrok.io'),).

设置提供者 - examples

¥Setting up the provider - examples

我们决定为每个提供者展示一个示例,而不是通用解释。你也可以 创建你自己的自定义提供程序

¥Instead of a generic explanation we decided to show an example for each provider. You can also create your own custom provider.

在以下示例中,前端应用将是 React 登录示例应用
它(前端应用)将在 http://localhost:3000 上运行。
Strapi(后端)将在 http://localhost:1337 上运行。

¥In the following examples, the frontend app will be the react login example app.
It (the frontend app) will be running on http://localhost:3000.
Strapi (the backend) will be running on http://localhost:1337.

使用 ngrok

Github 不接受 localhost 网址。
使用 ngrok 为后端应用提供服务。

¥Github doesn't accept localhost urls.
Use ngrok to serve the backend app.

ngrok http 1337

不要忘记使用生成的 ngrok url 更新后端配置文件 config/server.js 中的服务器 url 和前端应用中的服务器 url(如果使用 React 登录示例应用,则为环境变量 REACT_APP_BACKEND_URL)。

¥Don't forget to update the server url in the backend config file config/server.js and the server url in your frontend app (environment variable REACT_APP_BACKEND_URL if you use react login example app) with the generated ngrok url.

Github 配置

  • 访问 OAuth 应用列表页面 https://github.com/settings/developers

    ¥Visit the OAuth Apps list page https://github.com/settings/developers

  • 单击新建 OAuth 应用按钮

    ¥Click on New OAuth App button

  • 填写信息(替换为你自己的 ngrok url):

    ¥Fill the information (replace with your own ngrok url):

    • 应用名称:Strapi GitHub 授权

      ¥Application name: Strapi GitHub auth

    • 主页网址:https://65e60559.ngrok.io

      ¥Homepage URL: https://65e60559.ngrok.io

    • 应用说明:Strapi 提供者身份验证说明

      ¥Application description: Strapi provider auth description

    • 授权回调地址:https://65e60559.ngrok.io/api/connect/github/callback

      ¥Authorization callback URL: https://65e60559.ngrok.io/api/connect/github/callback

表带配置

  • 访问用户权限提供商设置页面
    http://localhost:1337/admin/settings/users-permissions/providers

    ¥Visit the User Permissions provider settings page
    http://localhost:1337/admin/settings/users-permissions/providers

  • 单击 GitHub 提供商

    ¥Click on the GitHub provider

  • 填写信息(替换为你自己的客户端 ID 和密码):

    ¥Fill the information (replace with your own client ID and secret):

    • 使能够:ON

      ¥Enable: ON

    • 客户编号:53de5258f8472c140917

      ¥Client ID: 53de5258f8472c140917

    • 客户秘密:fb9d0fe1d345d9ac7f83d7a1e646b37c554dae8b

      ¥Client Secret: fb9d0fe1d345d9ac7f83d7a1e646b37c554dae8b

    • 前端应用的重定向 URL:http://localhost:3000/connect/github/redirect

      ¥The redirect URL to your front-end app: http://localhost:3000/connect/github/redirect

你的配置已完成。启动后端和 React 登录示例应用,转到 http://localhost:3000 并尝试连接到你配置的提供者。

¥Your configuration is done. Launch the backend and the react login example app, go to http://localhost:3000 and try to connect to the provider your configured.

创建自定义提供程序

¥Creating a custom provider

你还可以使用 register 生命周期功能在 Strapi 应用的 src/index.js|ts 文件中创建自己的自定义提供程序。使用以下根据你的需要调整的代码示例:

¥You can also use the register lifecycle function to create your own custom provider in the src/index.js|ts file of your Strapi application. Use the following code example adjusted to your needs:

/src/index.js
module.exports = {
register({ strapi }) {
strapi
.plugin("users-permissions")
.service("providers-registry")
.add("example-provider-name", {
icon: "",
enabled: true,
grantConfig: {
key: "",
secret: "",
callback: `${strapi.config.server.url}/auth/example-provider-name/callback`,
scope: ["email"],
authorize_url: "https://awesome.com/authorize",
access_url: "https://awesome.com/token",
oauth: 2,
},
async authCallback({ accessToken, providers, purest }) {
// use whatever you want here to get the user info
return {
username: "test",
email: "test",
};
},
});
},
};

有关传递给 grantConfig 的参数的更多信息,请参阅 grant 文档。有关 purest 的更多信息,请参阅 purest 文档

¥For additional information on parameters passed to grantConfig, please refer to the grant documentation. For additional information about purest please refer to purest documentation.

设置前端

¥Setup the frontend

一旦你配置了 Strapi 和提供程序,你必须在前端应用中:

¥Once you have configured strapi and the provider, in your frontend app you have to :

  • 创建一个链接到 GET STRAPI_BACKEND_URL/api/connect/${provider} 的按钮(例如:https://strapi.mywebsite/api/connect/github)。

    ¥Create a button that links to GET STRAPI_BACKEND_URL/api/connect/${provider} (ex: https://strapi.mywebsite/api/connect/github).

  • 创建一个像 FRONTEND_URL/connect/${provider}/redirect 这样的前端路由,它必须处理 access_token 参数,并且必须使用 access_token 参数请求 STRAPI_BACKEND_URL/api/auth/${provider}/callback
    JSON 请求响应将为 { "jwt": "...", "user": {...} }

    ¥Create a frontend route like FRONTEND_URL/connect/${provider}/redirect that have to handle the access_token param and that have to request STRAPI_BACKEND_URL/api/auth/${provider}/callback with the access_token parameter.
    The JSON request response will be { "jwt": "...", "user": {...} }.

现在你可以发出经过身份验证的请求。更多信息请点击这里:令牌使用

¥Now you can make authenticated requests. More info here: token usage.

故障排除
  • 错误 429:这很可能是因为你的登录流程陷入了循环。如果要向后端发出新的请求,你需要等待几分钟或重新启动后端。

    ¥Error 429: It's most likely because your login flow fell into a loop. To make new requests to the backend, you need to wait a few minutes or restart the backend.

  • 授予:缺少会话或提供程序配置错误:这可能是由于很多事情造成的。

    ¥Grant: missing session or misconfigured provider: It may be due to many things.

    • 无法构建重定向网址:确保你已在 config/server.js 中设置后端 url:设置服务器 URL

      ¥The redirect url can't be built: Make sure you have set the backend url in config/server.js: Setting up the server url

    • 会话/cookie/缓存问题:你可以在私有标签中重试。

      ¥A session/cookie/cache problem: You can try again in a private tab.

    • ngrok 域的错误使用:检查你的网址并确保你使用 ngrok 网址而不是 http://localhost:1337。不要忘记检查示例应用中 src/config.js 处设置的后端 URL。

      ¥The incorrect use of a domain with ngrok: Check your urls and make sure that you use the ngrok url instead of http://localhost:1337. Don't forget to check the backend url set in the example app at src/config.js.

  • 你无法访问你的管理面板:这很可能是因为你使用带有 ngrok url 设置的后端 url 构建它,并且你停止/重新启动了 ngrok。你需要将后端 url 替换为新的 ngrok url,并再次运行 yarn buildnpm run build

    ¥You can't access your admin panel: It's most likely because you built it with the backend url set with a ngrok url and you stopped/restarted ngrok. You need to replace the backend url with the new ngrok url and run yarn build or npm run build again.

重设密码

¥Reset password

仅适用于使用电子邮件提供者注册的用户。

¥Can only be used for users registered using the email provider.

假设的一般流程:

¥The assumed general flow:

  1. 用户转到你忘记密码的页面。

    ¥The user goes to your forgotten password page.

  2. 用户输入他们的电子邮件地址。

    ¥The user enters their email address.

  3. 你忘记密码的页面会向后端发送请求,以向用户发送包含重置密码链接的电子邮件。

    ¥Your forgotten password page sends a request to the backend to send an email with the reset password link to the user.

  4. 用户收到电子邮件并单击特殊链接。

    ¥The user receives the email and clicks on the special link.

  5. 该链接会将用户重定向到你的重置密码页面。

    ¥The link redirects the user to your reset password page.

  6. 用户输入新密码。

    ¥The user enters their new password.

  7. 重置密码页面向后端发送包含新密码的请求。

    ¥The reset password page sends a request to the backend with the new password.

  8. 如果请求包含步骤 3 链接中包含的代码,则密码将被更新。

    ¥If the request contains the code contained in the link at step 3, the password is updated.

  9. 用户可以使用新密码登录。

    ¥The user can log in with the new password.

以下部分详细介绍了步骤 3 和 7。

¥The following section details steps 3 and 7.

¥Forgotten password: ask for the reset password link

此操作会向用户发送一封电子邮件,其中包含指向你的重置密码页面的链接。该链接将使用步骤 7 中 重设密码 所需的 url 参数 code 进行丰富。

¥This action sends an email to a user with the link to your reset password page. The link will be enriched with the url param code that is needed for the reset password at step 7.

首先,你必须指定以下内容:

¥First, you must specify the following:

  • 在管理面板中:设置 > 用户和权限插件 > 高级设置 > 重置密码页面,url 为你的重置密码页面。

    ¥In the admin panel: Settings > USERS & PERMISSIONS PLUGIN > Advanced Settings > Reset Password page, the url to your reset password page.

  • 在管理面板中:设置 > 用户和权限插件 > 电子邮件模板页面,发件人电子邮件。

    ¥In the admin panel: Settings > USERS & PERMISSIONS PLUGIN > Email Template page, the Shipper email.

然后,你忘记密码的页面必须向你的后端发出以下请求:

¥Then, your forgotten password page has to make the following request to your backend:

import axios from 'axios';

// Request API.
axios
.post('http://localhost:1337/api/auth/forgot-password', {
email: 'user@strapi.io', // user's email
})
.then(response => {
console.log('Your user received an email');
})
.catch(error => {
console.log('An error occurred:', error.response);
});

重设密码:发送新密码

¥Reset Password: send the new password

此操作将更新用户密码。这也适用于带有 resetPassword 突变的 GraphQL 插件

¥This action will update the user password. This also works with the GraphQL Plugin, with the resetPassword mutation.

你的重置密码页面必须向你的后端发出以下请求:

¥Your reset password page has to make the following request to your backend:

import axios from 'axios';

// Request API.
axios
.post('http://localhost:1337/api/auth/reset-password', {
code: 'privateCode', // code contained in the reset link of step 3.
password: 'userNewPassword',
passwordConfirmation: 'userNewPassword',
})
.then(response => {
console.log("Your user's password has been reset.");
})
.catch(error => {
console.log('An error occurred:', error.response);
});

电子邮件验证

¥Email validation

✏️ 注意

在生产中,确保设置了 url 配置属性。否则验证链接将重定向到 localhost。有关配置 此处 的更多信息。

¥In production, make sure the url config property is set. Otherwise the validation link will redirect to localhost. More info on the config here.

注册后,如果你将启用电子邮件确认设置为开,用户将通过电子邮件收到确认链接。用户必须单击它来验证其注册。

¥After registering, if you have set Enable email confirmation to ON, the user will receive a confirmation link by email. The user has to click on it to validate their registration.

确认链接示例:https://yourwebsite.com/api/auth/email-confirmation?confirmation=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaWF0IjoxNTk0OTgxMTE3LCJleHAiOjE1OTc1NzMxMTd9.0WeB-mvuguMyr4eY8CypTZDkunR--vZYzZH6h6sChFg

¥Example of the confirmation link: https://yourwebsite.com/api/auth/email-confirmation?confirmation=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MywiaWF0IjoxNTk0OTgxMTE3LCJleHAiOjE1OTc1NzMxMTd9.0WeB-mvuguMyr4eY8CypTZDkunR--vZYzZH6h6sChFg

如果需要,你可以通过提出以下请求重新发送确认电子邮件:

¥If needed you can re-send the confirmation email by making the following request:

import axios from 'axios';

// Request API.
axios
.post(`http://localhost:1337/api/auth/send-email-confirmation`, {
email: 'user@strapi.io', // user's email
})
.then(response => {
console.log('Your user received an email');
})
.catch(error => {
console.error('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);
};

模板化电子邮件

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

重设密码

¥Reset Password

  • USER(目的)

    ¥USER (object)

    • username

    • email

  • TOKEN 对应于生成的能够重置密码的令牌。

    ¥TOKEN corresponds to the token generated to be able to reset the password.

  • URL 是用户点击电子邮件中的链接后将被重定向到的链接。

    ¥URL is the link where the user will be redirected after clicking on it in the email.

  • SERVER_URL 是绝对服务器 url(在服务器配置中配置)。

    ¥SERVER_URL is the absolute server url (configured in server configuration).

电子邮件地址确认

¥Email address confirmation

  • USER(目的)

    ¥USER (object)

    • username

    • email

  • CODE 对应于生成的代码,以便能够确认用户电子邮件。

    ¥CODE corresponds to the CODE generated to be able confirm the user email.

  • URL 是确认代码的 Strapi 后端 URL(默认为 /auth/email-confirmation)。

    ¥URL is the Strapi backend URL that confirms the code (by default /auth/email-confirmation).

  • SERVER_URL 是绝对服务器 url(在服务器配置中配置)。

    ¥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,
};
💡 提示

你可以了解有关配置 此处 的更多信息。

¥You can learn more about configuration here.

创建自定义回调验证器

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

创建自定义密码验证

¥Creating a custom password validation

要在 API 级别添加密码验证,你可以在用户和权限插件的配置中创建一个传递给 validationRules 的自定义函数,如下例所示:

¥To add password validation at the API level, you can create a custom function passed to validationRules in the configuration of the Users & Permissions plugin, as in the following example:

/config/plugins.js|ts
  // ... other plugins configuration ...
// Users & Permissions configuration
'users-permissions': {
config: {
validationRules: {
validatePassword(value) {
if (value.length < 8) {
// custom error message
throw new Error('password should be more than 8 letters');
}

if (value.length > 24) {
// throws default error message
return false;
}

return true; // Validation passed
},
},
},
},