创建并添加自定义的用户与权限提供程序
🌐 Creating and adding a custom Users & Permissions provider
Page summary:通过在
src/index.js中注册自定义 OAuth 提供程序,并实现一个返回用户username的authCallback,为 Strapi 的用户与权限功能创建自定义 OAuth 提供程序,以便自动注册或登录。🌐 Create custom OAuth providers for Strapi's Users & Permissions feature by registering them in
src/index.jsand implementing anauthCallbackthat returns userusernamefor automatic registration or login.
Strapi 提供了一个 内置提供者 列表,用于 用户与权限功能。你也可以按照本指南创建自己的提供者。
🌐 Strapi provides a list of built-in providers for the Users & Permissions feature. You can also create your own provider following this guide.
你已经阅读了 用户与权限提供者文档 并理解了登录流程。
🌐 You have read the Users & Permissions providers documentation and understood the login flow.
创建自定义提供程序
🌐 Creating a custom provider
你可以使用 the register 生命周期函数 在 Strapi 应用的 src/index.js|ts 文件中创建你自己的自定义提供者。使用以下根据你的需求调整的代码示例:
🌐 You can 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:
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.
身份验证流程如何工作
🌐 How authentication flow works
authCallback 函数返回的对象必须至少包含 username 和 email 属性。Strapi 使用这个返回的电子邮件地址来自动处理注册和登录的认证流程:
🌐 The object returned by the authCallback function must contain at least username and email properties. Strapi uses this returned email address to automatically resolve the authentication flow for both registration and login:
- 如果用户不存在:Strapi 会在返回的
email和username下注册一个新用户,然后登录该用户,返回 JWT 和用户对象。 - 如果用户已存在:Strapi 会检索与该
email匹配的现有用户并将其登录,返回 JWT 和用户对象。
由于这种设计,你无需在自定义提供程序中实现单独的查找或注册逻辑。你只需要确保你的 authCallback 从外部提供程序获取用户的资料,并返回用户的 email 和 username。
🌐 Because of this design, you do not need to implement separate lookup or registration logic inside your custom provider. You only need to ensure your authCallback fetches the user's profile from the external provider and returns the user's email and username.
前端设置
🌐 Frontend setup
配置 Strapi 和提供程序后,你必须在前端应用中:
🌐 Once you have configured Strapi and the provider, in your frontend application you must:
- 创建一个链接到
GET STRAPI_BACKEND_URL/api/connect/${provider}的按钮(例如,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": {...} }。
现在你可以按照令牌使用中描述的方式进行身份验证请求。
🌐 Now you can make authenticated requests, as described in token usage.
- 未提供电子邮件:当
authCallback未能返回有效的email地址时,会发生此错误。- 确保你的提供者应用已配置正确的 OAuth 范围(例如
email或profile)以请求用户的电子邮件。 - 检查身份提供者是否确实在有效载荷中返回了电子邮件。请注意,一些用户可能在身份提供者端隐藏了他们的电子邮件地址或将其设置为私密。
- 确保你的提供者应用已配置正确的 OAuth 范围(例如
- 错误 429:这很可能是因为你的登录流程进入了循环。要向后端发起新的请求,你需要等待几分钟或重启后端。
- Grant:缺少会话或提供程序配置错误:可能由于多种原因造成。
- 无法构建重定向 URL:请确保已在
config/server.js中设置后端 URL:设置服务器 URL - 会话/Cookie/缓存问题:你可以尝试在私密窗口中重新尝试。
- 使用 ngrok 域名不正确:检查你的 URL,并确保使用 ngrok URL 而不是
http://localhost:1337。不要忘记检查示例应用中设置的后端 URL,位于src/config.js。
- 无法构建重定向 URL:请确保已在
- 你无法访问你的管理面板:最可能的原因是你使用 ngrok URL 设置了后端 URL 构建它,然后你停止/重新启动了 ngrok。你需要将后端 URL 替换为新的 ngrok URL,然后再次运行
yarn build或npm run build。
重置密码
🌐 Reset password
只能用于通过电子邮件提供商注册的用户。
- Forgot & Reset flow
- Change the password flow
假定的一般流程:
🌐 The assumed general flow:
- 用户访问你的忘记密码页面。
- 用户输入他们的电子邮件地址。
- 你忘记密码的页面会向后端发送请求,以向用户发送包含重置密码链接的电子邮件。
- 用户收到电子邮件并单击特殊链接。
- 该链接会将用户重定向到你的重置密码页面。
- 用户输入新密码。
- 重置密码页面 将新密码发送到后端。
- 如果请求包含步骤 3 链接中包含的代码,则密码将被更新。
- 用户可以使用新密码登录。
以下部分详细介绍了步骤 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指向你的重置密码页面。 - 在管理面板中:设置 > 用户与权限插件 > 电子邮件模板 页面,点击 发货人电子邮件。
然后,你的忘记密码页面必须向你的后端发送以下请求:
🌐 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
此操作将更新用户密码。
这同样适用于 GraphQL 插件,使用 resetPassword 变更。
🌐 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);
});
你也可以通过 /change-password API 端点更新已认证用户的密码:
🌐 You can also update an authenticated user password through the /change-password API endpoint:
import axios from 'axios';
// Request API.
axios.post(
'http://localhost:1337/api/auth/change-password',
{
currentPassword: 'currentPassword',
password: 'userNewPassword',
passwordConfirmation: 'userNewPassword',
},
{
headers: {
Authorization: 'Bearer <user jwt>',
},
}
);
电子邮件验证
🌐 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 应用添加新提供者
🌐 Adding a new provider to your Strapi application
本文件可能没有与 Strapi 5 保持最新,并且仍在进行中。同时, contributions 非常欢迎。
Grant 提供多个常用 OAuth 提供商的配置。 Custom 也支持提供商。
你可以在此查看并试用 200 多个支持的提供商: OAuth Playground。