创建和添加自定义用户和权限提供程序
¥Creating and adding a custom Users & Permissions provider
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
你可以使用 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.
前端设置
¥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)。¥Create a button that links to
GET STRAPI_BACKEND_URL/api/connect/${provider}(e.g.,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}/redirectthat have to handle theaccess_tokenparam and that have to requestSTRAPI_BACKEND_URL/api/auth/${provider}/callbackwith theaccess_tokenparameter.
The JSON request response will be{ "jwt": "...", "user": {...} }.
现在你可以发出经过身份验证的请求,如 令牌使用 中所述。
¥Now you can make authenticated requests, as described in 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.