用户与权限提供者
🌐 Users & Permissions providers
Strapi 提供了一套预定义的内置提供者,用于用户与权限功能。本页面解释了登录流程的工作原理、如何设置服务器 URL,并列出许多常见第三方提供者的示例。
🌐 Strapi comes with a predefined set of built-in providers for the Users & Permissions feature. The present page explains how the login flow works, how to set up the server URL, and list many examples for common 3rd-party providers.
如果你想创建自己的自定义提供者,请参考专用指南。
🌐 If you're looking to create your own custom provider, please refer to the dedicated guide.
了解登录流程
🌐 Understanding the login flow
Grant 和 Purest 允许你使用 OAuth 和 OAuth2 提供程序来在你的应用中启用认证。
为了更好地理解,请查看以下登录流程描述。示例使用 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.
假设:
🌐 Let's say that:
- Strapi 的后端位于:
strapi.website.com,并且 - 你的应用前端位于:
website.com
- 用户在你的前端应用(
https://website.com)上点击你的按钮connect with Github。 - 前端将标签重定向到后端 URL:
https://strapi.website.com/api/connect/github。 - 后端将选项卡重定向到用户登录的 GitHub 登录页面。
- 完成后,Github 会将标签页重定向到后端 URL:
https://strapi.website.com/api/connect/github/callback?code=abcdef。 - 后端使用给定的
code从 Github 获取一个access_token,该access_token可以在一段时间内用于向 Github 发起授权请求以获取用户信息。 - 然后,后台将标签页重定向到你选择的 URL,并带上参数
access_token(例如:http://website.com/connect/github/redirect?access_token=eyfvg)。 - 前端(
http://website.com/connect/github/redirect)使用https://strapi.website.com/api/auth/github/callback?access_token=eyfvg调用后端,后端返回带有其jwt的 Strapi 用户资料。
(在底层,后端会向 Github 请求用户的资料,并在 Github 用户的电子邮件地址和 Strapi 用户的电子邮件地址上进行匹配)。 - 前端现在拥有用户的
jwt,这意味着用户已连接,并且前端可以向后端发起经过身份验证的请求!
可以在此处找到处理此流程的前端应用示例: react login example application。
设置服务器网址
🌐 Setting up the server URL
在设置提供程序之前,你必须在 /config/server 中指定后端的绝对 URL:
🌐 Before setting up a provider you must specify the absolute URL of your backend in /config/server:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
host: env('HOST', '0.0.0.0'),
port: env.int('PORT', 1337),
url: env('', 'http://localhost:1337'),
});
export default ({ 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 到你的 localhost URL(例如,url: env('', 'https://5299e8514242.ngrok.io'),)建立一个代理隧道。
设置提供者 - 示例
🌐 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.
在以下示例中,前端应用将在 http://localhost:3000 上运行,而 Strapi(即后端服务器)将在 http://localhost:1337 上运行。
如果你想创建并添加新的自定义提供程序,请参阅以下指南:
🌐 If you want to create and add a new custom provider, please refer to the following guide: