用户和权限插件
¥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.
- Axios
- Postman
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);
});
如果你使用 Postman,请将正文设置为 raw 并选择 JSON 作为数据格式:
¥If you use Postman, set the body to raw and select JSON as your data format:
{
"identifier": "user@strapi.io",
"password": "strapiPassword"
}
如果请求成功,你将在 jwt
键中收到用户的 JWT:
¥If the request is successful you will receive the user's JWT in the jwt
key:
{
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTc2OTM4MTUwLCJleHAiOjE1Nzk1MzAxNTB9.UgsjjXkAZ-anD257BF7y1hbjuY3ogNceKfTAQtzDEsU",
"user": {
"id": 1,
"username": "user",
...
}
}
令牌使用
¥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 theJWT_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.
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
// ...
'users-permissions': {
config: {
jwt: {
expiresIn: '7d',
},
},
},
// ...
});
export default ({ 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:
- JavaScript
- TypeScript
module.exports = ({ env }) => ({
// ...
"users-permissions": {
config: {
register: {
allowedFields: ["nickname"],
},
},
},
// ...
});
export default ({ 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
用户进入你的前端应用 (
https://website.com
) 并单击你的按钮connect with Github
。¥The user goes on your frontend app (
https://website.com
) and clicks on your buttonconnect with Github
.前端将选项卡重定向到后端 URL:
https://strapi.website.com/api/connect/github
。¥The frontend redirects the tab to the backend URL:
https://strapi.website.com/api/connect/github
.后端将选项卡重定向到用户登录的 GitHub 登录页面。
¥The backend redirects the tab to the GitHub login page where the user logs in.
完成后,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
.后端使用给定的
code
从 Github 获取access_token
,该access_token
可用于在一段时间内向 Github 发出授权请求以获取用户信息。¥The backend uses the given
code
to get anaccess_token
from Github that can be used for a period of time to make authorized requests to Github to get the user info.然后,后端使用参数
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
).前端 (
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 withhttps://strapi.website.com/api/auth/github/callback?access_token=eyfvg
that returns the Strapi user profile with itsjwt
.
(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).前端现在拥有用户的
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
- 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 到本地主机 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
.
- GitHub
- AWS Cognito
- Discord
- Twitch
- VK
- CAS
- Auth0
- Patreon
- Keycloak
使用 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
使用 ngrok
Facebook 不接受 localhost
网址。
使用 ngrok
为后端应用提供服务。
¥Facebook 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.
脸书配置
访问开发者应用列表页面
https://developers.facebook.com/apps/¥Visit the Developer Apps list page
https://developers.facebook.com/apps/单击添加新应用按钮
¥Click on Add a New App button
在模式中填写显示名称并创建应用
¥Fill the Display Name in the modal and create the app
设置 Facebook 登录产品
¥Setup a Facebook Login product
单击左侧菜单中的产品 > Facebook 登录 > 设置链接
¥Click on the PRODUCTS > Facebook login > Settings link in the left menu
填写信息并保存(替换为你自己的 ngrok url):
¥Fill the information and save (replace with your own ngrok url):
有效的 OAuth 重定向 URI:
https://65e60559.ngrok.io/api/connect/facebook/callback
¥Valid OAuth Redirect URIs:
https://65e60559.ngrok.io/api/connect/facebook/callback
然后,点击左侧菜单中的“设置”
¥Then, click on Settings in the left menu
然后在基本链接上
¥Then on Basic link
你应该会看到你的应用 ID 和密码,保存起来供以后使用
¥You should see your Application ID and secret, save them for later
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Facebook 提供商
¥Click on the Facebook provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:2408954435875229
¥Client ID: 2408954435875229
客户秘密:4fe04b740b69f31ea410b9391ff3b5b0
¥Client Secret: 4fe04b740b69f31ea410b9391ff3b5b0
前端应用的重定向 URL:
http://localhost:3000/connect/facebook/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/facebook/redirect
使用 ngrok
Google 接受 localhost
网址。
不需要使用 ngrok
。
¥Google accepts the localhost
urls.
The use of ngrok
is not needed.
谷歌配置
访问 Google 开发者控制台
https://console.developers.google.com/¥Visit the Google Developer Console
https://console.developers.google.com/单击顶部菜单中的选择项目下拉菜单
¥Click on the Select a project dropdown in the top menu
然后单击“新建项目”按钮
¥Then click NEW PROJECT button
填写项目名称输入并创建
¥Fill the Project name input and create
创建应用时请等待几秒钟。
¥Wait a few seconds while the application is created.
在项目下拉列表中,选择你的新项目
¥On the project dropdown, select your new project
单击 API 卡下的转到 API 概述
¥Click on Go to APIs overview under the APIs card
然后单击左侧菜单中的凭据链接
¥Then click on the Credentials link in the left menu
单击 OAuth 同意屏幕按钮
¥Click on OAuth consent screen button
选择外部并点击创建
¥Choose External and click on create
填写应用名称并保存
¥Fill the Application name and save
然后单击创建凭据按钮
¥Then click on Create credentials button
选择 OAuth 客户端 ID 选项
¥Choose OAuth client ID option
填写信息:
¥Fill the information:
名称:
Strapi Auth
¥Name:
Strapi Auth
授权重定向 URI:
http://localhost:1337/api/connect/google/callback
¥Authorized redirect URIs:
http://localhost:1337/api/connect/google/callback
单击你刚刚创建的客户端的 OAuth 2.0 客户端 ID 名称
¥Click on OAuth 2.0 Client IDs name of the client you just created
你应该会看到你的应用 ID 和密码,保存起来供以后使用
¥You should see your Application ID and secret, save them for later
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers点击 Google 提供商
¥Click on the Google provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:226437944084-o2mojv5i4lfnng9q8kq3jkf5v03avemk.apps.googleusercontent.com
¥Client ID: 226437944084-o2mojv5i4lfnng9q8kq3jkf5v03avemk.apps.googleusercontent.com
客户秘密:aiTbMoiuJQflSBy6uQrfgsni
¥Client Secret: aiTbMoiuJQflSBy6uQrfgsni
前端应用的重定向 URL:
http://localhost:3000/connect/google/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/google/redirect
使用 ngrok
AWS Cognito 接受 localhost
URL。
不需要使用 ngrok
。
¥AWS Cognito accepts the localhost
urls.
The use of ngrok
is not needed.
AWS Cognito 配置
访问 AWS 管理控制台
https://aws.amazon.com/console/¥Visit the AWS Management Console
https://aws.amazon.com/console/如果需要,请在右上角“支持”下拉列表旁边选择你的区域
¥If needed, select your Region in the top right corner next to the Support dropdown
选择左上角的服务下拉菜单
¥Select the Services dropdown in the top left corner
单击
Security, Identity & Compliance
部分中的 Cognito¥Click on Cognito in the
Security, Identity & Compliance
section然后单击管理用户池按钮
¥Then click on the Manage User Pools button
如果适用,创建或使用现有用户池。你将在下文中找到创建用户池的教程
https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html¥If applicable either create or use an existing user pool. You will find hereafter a tutorial to create a User Pool
https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html转到 Cognito 用户池中的“应用客户端”部分,创建一个名为
Strapi Auth
的新客户端并设置所有参数,然后单击“创建应用客户端”¥Go to the App clients section in your cognito user pool and create a new client with the name
Strapi Auth
and set all the parameters and then click on Create app client你现在应该有一个应用客户端 ID,通过单击“显示详细信息”按钮,你将能够看到应用客户端密钥。请务必将这两个值应用客户端 ID 和应用客户端密钥复制到某处,以便稍后在 Strapi 中配置 AWS Cognito 提供程序时使用。
¥You should now have an App client id and by clicking on the button Show Details you will be able to see the App client secret. Do copy those two values App client id and App client secret somewhere for later use when configuring the AWS Cognito provider in Strapi.
转到应用集成部分,然后单击应用客户端设置
¥Go to the App integration section and click on App client settings
查找名为
Strapi Auth
的应用客户端,并通过在新创建的应用客户端的启用身份提供商部分中选中它来启用 Cognito 用户池¥Look for your app client named
Strapi Auth
and enable Cognito User Pool by checking it in the Enabled Identity Providers section of your newly created App client使用值
http://localhost:1337/api/connect/cognito/callback
或你的 AWS Cognito 提供者在 Strapi 中提供的值填写你的回调 URL 和注销 URL¥Fill in your callback URL and Sign out URL with the value
http://localhost:1337/api/connect/cognito/callback
or the one provided by your AWS Cognito provider in Strapi在 Oauth 2.0 部分中,为允许的 OAuth 流程选择
Authorization code grant
和Implicit grant
,为允许的 OAuth 范围选择email
、openid
和profile
¥In the Oauth 2.0 section select
Authorization code grant
andImplicit grant
for the Allowed OAuth Flows and selectemail
,openid
andprofile
for the Allowed OAuth Scopes你现在可以单击“保存更改”,如果你已经配置了域名,那么你应该能够看到指向“启动托管 UI”的链接。你可以单击它以显示 AWS Cognito 登录页面。如果你尚未配置域名,请使用页面右下角的链接选择域名来配置你的域名。在该页面上,你将有一个
Amazon Cognito Domain
部分,其中已设置Domain prefix
。输入用于 Amazon Cognito 托管的注册和登录页面的域前缀,该域前缀与.auth.YOUR_REGION.amazoncognito.com
一起将成为稍后你的 Strapi 配置的主机 URI(子域)值。¥You can now click on Save changes and if you have already configured your domain name then you should be able to see a link to the Launch Hosted UI. You can click on it in order to display the AWS Cognito login page. In case you haven't yet configured your domain name, use the link Choose domain name at the bottom right of the page in order to configure your domain name. On that page you will have an
Amazon Cognito Domain
section where aDomain prefix
is already setup. Type a domain prefix to use for the sign-up and sign-in pages that are hosted by Amazon Cognito, this domain prefix together with the.auth.YOUR_REGION.amazoncognito.com
will be the Host URI (Subdomain) value for your strapi configuration later on.
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Cognito 提供商
¥Click on the Cognito provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:填写 App 客户端 id(
5bd7a786qdupjmi0b3s10vegdt
)¥Client ID: fill in the App client id (
5bd7a786qdupjmi0b3s10vegdt
)客户秘密:填写 App 客户端密钥(
19c5c78dsfsdfssfsdfhpdb4nkpb145vesdfdsfsffgh7vwd6g45jlipbpb
)¥Client Secret: fill in the App client secret (
19c5c78dsfsdfssfsdfhpdb4nkpb145vesdfdsfsffgh7vwd6g45jlipbpb
)主机 URI(子域):填写你之前复制的 URL 值 (
myapp67b50345-67b50b17-local.auth.eu-central-1.amazoncognito.com
)¥Host URI (Subdomain): fill in the URL value that you copied earlier (
myapp67b50345-67b50b17-local.auth.eu-central-1.amazoncognito.com
)前端应用的重定向 URL:如果你使用的是 Strapi React-login https://github.com/strapi/strapi-examples/tree/master/examples/login-react/,请使用
http://localhost:3000/connect/cognito/redirect
,但如果你还没有前端应用来测试你的 Cognito 配置,则可以使用以下 URLhttp://localhost:1337/api/auth/cognito/callback
¥The redirect URL to your front-end app: if you are using strapi react-login https://github.com/strapi/strapi-examples/tree/master/examples/login-react/ use
http://localhost:3000/connect/cognito/redirect
but if you do not yet have a front-end app to test your Cognito configuration you can then use the following URLhttp://localhost:1337/api/auth/cognito/callback
使用 ngrok
Twitter 不接受 localhost
网址。
使用 ngrok
为后端应用提供服务。
¥Twitter 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.
推特配置
访问应用列表页面
https://developer.twitter.com/en/apps¥Visit the Apps list page
https://developer.twitter.com/en/apps单击创建应用按钮
¥Click on Create an app button
填写信息(替换为你自己的 ngrok url):
¥Fill the information (replace with your own ngrok url):
应用名称:Strapi Twitter 授权
¥App name: Strapi Twitter auth
应用说明:这是 Strapi 身份验证的演示应用
¥Application description: This is a demo app for Strapi auth
告诉我们这个应用将如何使用:* 在这里写一条足够长的消息 -
¥Tell us how this app will be used: - here write a message enough long -
在此过程结束时,你应该会看到你的应用 ID 和密码,保存它们以供以后使用
¥At the end of the process you should see your Application ID and secret, save them for later
转到你的应用设置并单击编辑身份验证设置
¥Go to you app setting and click on edit Authentication settings
启用第 3 方身份验证并请求用户的电子邮件地址
¥Enable 3rd party authentication AND Request email address from users
填写信息(替换为你自己的 ngrok url):
¥Fill the information (replace with your own ngrok url):
回调网址:
https://65e60559.ngrok.io/api/connect/twitter/callback
¥Callback URLs:
https://65e60559.ngrok.io/api/connect/twitter/callback
网址:
https://65e60559.ngrok.io
¥Website URL:
https://65e60559.ngrok.io
隐私政策:
https://d73e70e88872.ngrok.io
¥Privacy policy:
https://d73e70e88872.ngrok.io
服务条款:
https://d73e70e88872.ngrok.io
¥Terms of service:
https://d73e70e88872.ngrok.io
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Twitter 提供商
¥Click on the Twitter provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
API 密钥:yfN4ycGGmKXiS1njtIYxuN5IH
¥API Key: yfN4ycGGmKXiS1njtIYxuN5IH
API 秘密:Nag1en8S4VwqurBvlW5OaFyKlzqrXFeyWhph6CZlpGA2V3VR3T
¥Api Secret: Nag1en8S4VwqurBvlW5OaFyKlzqrXFeyWhph6CZlpGA2V3VR3T
前端应用的重定向 URL:
http://localhost:3000/connect/twitter/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/twitter/redirect
使用 ngrok
Discord 接受 localhost
网址。
不需要使用 ngrok
。
¥Discord accepts the localhost
urls.
The use of ngrok
is not needed.
Discord 配置
访问开发者门户上的应用列表页面
https://discordapp.com/developers/applications/¥Visit the Apps list page on the developer portal
https://discordapp.com/developers/applications/单击新应用按钮
¥Click on New application button
填写名称并创建
¥Fill the name and create
单击左侧菜单中的 OAuth2
¥Click on OAuth2 in the left menu
然后单击添加重定向按钮
¥And click on Add redirect button
在重定向输入中填写
http://localhost:1337/api/connect/discord/callback
URL 并保存¥Fill the Redirect input with
http://localhost:1337/api/connect/discord/callback
URL and save单击左侧菜单中的一般信息
¥Click on General information in the left menu
你应该会看到你的应用 ID 和密码,保存起来供以后使用
¥You should see your Application ID and secret, save them for later
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Discord 提供商
¥Click on the Discord provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:665118465148846081
¥Client ID: 665118465148846081
客户秘密:iJbr7mkyqyut-J2hGvvSDch_5Dw5U77J
¥Client Secret: iJbr7mkyqyut-J2hGvvSDch_5Dw5U77J
前端应用的重定向 URL:
http://localhost:3000/connect/discord/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/discord/redirect
使用 ngrok
Twitch 接受 localhost
网址。
不需要使用 ngrok
。
¥Twitch accepts the localhost
urls.
The use of ngrok
is not needed.
抽搐配置
访问开发者控制台上的应用列表页面
https://dev.twitch.tv/console/apps¥Visit the Apps list page on the developer console
https://dev.twitch.tv/console/apps单击注册你的应用按钮
¥Click on Register Your Application button
填写信息:
¥Fill the information:
名称:Strapi 授权
¥Name: Strapi auth
OAuth 重定向 URL:
http://localhost:1337/api/connect/twitch/callback
¥OAuth Redirect URLs:
http://localhost:1337/api/connect/twitch/callback
类别:选择一个类别
¥Category: Choose a category
单击新应用的管理按钮
¥Click on Manage button of your new app
使用“新密钥”按钮生成新的客户端密钥
¥Generate a new Client Secret with the New Secret button
你应该会看到你的应用 ID 和密码,保存起来供以后使用
¥You should see your Application ID and secret, save them for later
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Twitch 提供商
¥Click on the Twitch provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:amuy279g8wt68qlht3u4gek4oykh5j
¥Client ID: amuy279g8wt68qlht3u4gek4oykh5j
客户秘密:dapssh10uo97gg2l25qufr8wen3yr6
¥Client Secret: dapssh10uo97gg2l25qufr8wen3yr6
前端应用的重定向 URL:
http://localhost:3000/connect/twitch/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/twitch/redirect
使用 ngrok
Facebook 不接受 localhost
网址。
使用 ngrok
为后端应用提供服务。
¥Facebook 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.
Instagram 配置
访问开发者应用列表页面
https://developers.facebook.com/apps/¥Visit the Developer Apps list page
https://developers.facebook.com/apps/单击添加新应用按钮
¥Click on Add a New App button
在模式中填写显示名称并创建应用
¥Fill the Display Name in the modal and create the app
设置 Instagram 产品
¥Setup an Instagram product
单击左侧菜单中的产品 > Instagram > 基本显示链接
¥Click on the PRODUCTS > Instagram > Basic Display link in the left menu
然后单击“创建新应用”按钮(并使模式生效)
¥Then click on the Create new application button (and valid the modal)
填写信息(替换为你自己的 ngrok url):
¥Fill the information (replace with your own ngrok url):
有效的 OAuth 重定向 URI:
https://65e60559.ngrok.io/api/connect/instagram/callback
¥Valid OAuth Redirect URIs:
https://65e60559.ngrok.io/api/connect/instagram/callback
取消授权:
https://65e60559.ngrok.io
¥Deauthorize:
https://65e60559.ngrok.io
数据删除请求:
https://65e60559.ngrok.io
¥Data Deletion Requests:
https://65e60559.ngrok.io
在 Instagram 基本显示的应用审核中,单击“添加到 instagram_graph_user_profile 的提交”。
¥On the App Review for Instagram Basic Display click on Add to submission for instagram_graph_user_profile.
你应该会看到你的应用 ID 和密码,保存起来供以后使用
¥You should see your Application ID and secret, save them for later
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Instagram 提供商
¥Click on the Instagram provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:563883201184965
¥Client ID: 563883201184965
客户秘密:f5ba10a7dd78c2410ab6b8a35ab28226
¥Client Secret: f5ba10a7dd78c2410ab6b8a35ab28226
前端应用的重定向 URL:
http://localhost:3000/connect/instagram/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/instagram/redirect
使用 ngrok
VK 接受 localhost
网址。
不需要使用 ngrok
。
¥VK accepts the localhost
urls.
The use of ngrok
is not needed.
VK 配置
访问应用列表页面
https://vk.com/apps?act=manage¥Visit the Apps list page
https://vk.com/apps?act=manage单击创建应用按钮
¥Click on Create app button
填写信息:
¥Fill the information:
标题:Strapi 授权
¥Title: Strapi auth
平台:选择网站选项
¥Platform: Choose Website option
网站地址:
http://localhost:1337
¥Website address:
http://localhost:1337
基域:
localhost
¥Base domain:
localhost
单击左侧菜单中的“设置”链接
¥Click on the Settings link in the left menu
单击 Open API 链接以启用此选项
¥Click on the Open API link to enable this option
填写信息:
¥Fill the information:
授权重定向网址:
http://localhost:1337/api/connect/vk/callback
¥Authorized redirect URL:
http://localhost:1337/api/connect/vk/callback
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers点击 VK 提供商
¥Click on the VK provider
填写信息:
¥Fill the information:
使能够:
ON
¥Enable:
ON
客户编号:7276416
¥Client ID: 7276416
客户秘密:cFBUSghLXGuxqnCyw1N3
¥Client Secret: cFBUSghLXGuxqnCyw1N3
前端应用的重定向 URL:
http://localhost:3000/connect/vk/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/vk/redirect
使用 ngrok
LinkedIn 接受 localhost
网址。
不需要使用 ngrok
。
¥LinkedIn accepts the localhost
urls.
The use of ngrok
is not needed.
领英配置
访问应用列表页面
https://www.linkedin.com/developers/apps¥Visit the Apps list page
https://www.linkedin.com/developers/apps单击创建应用按钮
¥Click on Create app button
填写信息:
¥Fill the information:
应用名称:Strapi 授权
¥App name: Strapi auth
领英页面:输入与应用关联的 LinkedIn 页面名称,或单击“创建新的 LinkedIn 页面”以创建新页面
¥LinkedIn Page: Enter a LinkedIn page name to associate with the app or click Create a new LinkedIn Page to create a new one
应用徽标:上传至少 100x100 像素的方形图片。
¥App Logo: Upload a square image that is at least 100x100 pixels.
单击创建应用以创建应用
¥Click on the Create app to create the app
在应用页面上单击“身份验证”选项卡
¥On the app page click on Auth tab
填写信息:
¥Fill the information:
授权重定向网址:
http://localhost:1337/api/connect/linkedin/callback
¥Authorized redirect URL:
http://localhost:1337/api/connect/linkedin/callback
在应用页面上单击“产品”选项卡。
¥On the app page click on Products tab.
从产品列表中选择
Sign In with LinkedIn
来启用它。¥Select
Sign In with LinkedIn
from the product list to enable it.
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 LinkedIn 提供商
¥Click on the LinkedIn provider
填写信息:
¥Fill the information:
使能够:
ON
¥Enable:
ON
客户编号:84witsxk641rlv
¥Client ID: 84witsxk641rlv
客户秘密:HDXO7a7mkrU5a6WN
¥Client Secret: HdXO7a7mkrU5a6WN
前端应用的重定向 URL:
http://localhost:3000/connect/linkedin/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/linkedin/redirect
使用 ngrok
远程 CAS 服务器可以配置为接受 localhost
URL,或者你可以在本地运行自己的 CAS 服务器来接受它们。
¥A remote CAS server can be configured to accept localhost
URLs or you can run your own CAS server locally that accepts them.
不需要使用 ngrok
。
¥The use of ngrok
is not needed.
CAS 配置
CAS 是一款 SSO 服务器,支持多种不同的方法来验证用户身份、检索用户属性以及通过 SAML、OIDC 和 CAS 协议等协议将该信息传递给应用。如果部署的 CAS 支持 OIDC,则 Strapi 可以使用 CAS 服务器进行身份验证。
¥CAS is an SSO server that supports many different methods of verifying a users identity, retrieving attributes out the user and communicating that information to applications via protocols such as SAML, OIDC, and the CAS protocol. Strapi can use a CAS server for authentication if CAS is deployed with support for OIDC.
CAS 可能已被你的公司或组织使用,或者你可以通过克隆 CAS 叠加 项目或使用较新的 CAS 初始化器 创建覆盖项目来设置本地 CAS 服务器。
¥CAS could already be used by your company or organization or you can setup a local CAS server by cloning the CAS Overlay project or using the newer CAS Initializr to create an overlay project.
必须配置 CAS 服务器,使其可以充当 OpenID 连接提供者
¥The CAS server must be configured so it can act as an OpenID Connect Provider
已知 CAS 版本 6.3.x 及更高版本可与 Strapi 配合使用,但支持 OIDC 的旧版本也可以使用。
¥CAS version 6.3.x and higher is known to work with Strapi but older versions that support OIDC may work.
为 Strapi 定义 CAS OIDC 服务并将其存储在正在使用的 CAS 服务注册表中。
¥Define a CAS OIDC service for Strapi and store it in whichever CAS service registry is being used.
对于本地 Strapi 部署,CAS 服务定义可能如下所示:
¥The CAS service definition might look something like this for a local strapi deployment:
{
"@class": "org.apereo.cas.services.OidcRegisteredService",
"clientId": "thestrapiclientid",
"clientSecret": "thestrapiclientsecret",
"bypassApprovalPrompt": true,
"serviceId": "^http(|s)://localhost:1337/.*",
"name": "Local Strapi",
"id": 20201103,
"evaluationOrder": 50,
"attributeReleasePolicy": {
"@class": "org.apereo.cas.services.ReturnMappedAttributeReleasePolicy",
"allowedAttributes": {
"@class": "java.util.TreeMap",
"strapiemail": "groovy { return attributes['mail'].get(0) }",
"strapiusername": "groovy { return attributes['username'].get(0) }"
}
}
}
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/plugins/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/plugins/users-permissions/providers单击 Cas 提供商
¥Click on the Cas provider
填写信息:
¥Fill the information:
使能够:
ON
¥Enable:
ON
客户编号:thestrapiclientid
¥Client ID: thestrapiclientid
客户秘密:thestrapiclientsecret
¥Client Secret: thestrapiclientsecret
前端应用的重定向 URL:
http://localhost:1337/api/connect/cas/redirect
¥The redirect URL to your front-end app:
http://localhost:1337/api/connect/cas/redirect
提供者子域,以便以下 URL 对于你所定位的 CAS 部署是正确的:
¥The Provider Subdomain such that the following URLs are correct for the CAS deployment you are targeting:
authorize_url: https://[subdomain]/oidc/authorize
access_url: https://[subdomain]/oidc/token
profile_url: https://[subdomain]/oidc/profile例如,如果使用以下登录 URL 在本地运行 CAS:
https://localhost:8443/cas/login
,提供者子域的值为localhost:8443/cas
。¥For example, if running CAS locally with a login URL of:
https://localhost:8443/cas/login
, the value for the provider subdomain would belocalhost:8443/cas
.
使用 ngrok
Reddit 接受 localhost
网址。
不需要使用 ngrok
。
¥Reddit accepts the localhost
urls.
The use of ngrok
is not needed.
红迪网配置
访问 Reddit 授权应用首选项页面
https://www.reddit.com/prefs/apps¥Visit the Reddit authorized applications preferences page
https://www.reddit.com/prefs/apps单击创建另一个应用...靠近底部的按钮
¥Click on the create another app... button near the bottom
选择网络应用类型
¥Select web app for the type
填写名称并重定向 uri 输入
¥Fill the name and redirect uri input in
单击创建应用按钮
¥Click the create app button
请注意,客户端 ID 位于应用类型(Web 应用)下
¥Note that the Client ID is located under the app type (web app)
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Reddit 提供商
¥Click on the Reddit provider
填写信息(替换为你自己的客户端 ID 和密码):
¥Fill the information (replace with your own client ID and secret):
使能够:
ON
¥Enable:
ON
客户编号:hmxSBOit0SCjSQ
¥Client ID: hmxSBOit0SCjSQ
客户秘密:gwR9hCjK_PMYVYNGeDLS4WLB8g7xqg
¥Client Secret: gwR9hCjK_PMYVYNGeDLS4WLB8g7xqg
前端应用的重定向 URL:
http://localhost:3000/connect/reddit/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/reddit/redirect
使用 ngrok
Auth0 接受 localhost
url。
不需要使用 ngrok
。
¥Auth0 accepts the localhost
urls.
The use of ngrok
is not needed.
Auth0 配置
访问你的 Auth0 租户仪表板
¥Visit your Auth0 tenant dashboard
在 API 部分,创建一个新的 API
¥In API section, create a new API
在应用中,创建
machine-to-machine
应用并选择刚刚创建的 API¥In application, create a
machine-to-machine
application and select the API that you have just created在此应用的设置中设置以下值:
¥In settings of this app set these values:
允许的回调 URL:
http://localhost:1337/api/connect/auth0/callback
¥Allowed Callback URLs:
http://localhost:1337/api/connect/auth0/callback
允许的注销 URL:
http://localhost:3000
¥Allowed Logout URLs:
http://localhost:3000
允许的 Web 来源:
http://localhost:3000
¥Allowed Web Origins:
http://localhost:3000
在设置底部,显示 "高级设置" 并转到 "补助金类型"。确保检查/启用这些授权:
¥At the bottom of settings, show "Advanced Settings" and go to the "Grant Types". Ensure that these grants are checked/enabled:
隐含的
¥Implicit
授权码
¥Authorization Code
刷新令牌
¥Refresh Token
客户凭证
¥Client Credentials
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Auth0 提供商
¥Click on the Auth0 provider
填写信息:
¥Fill the information:
使能够:
ON
¥Enable:
ON
客户编号:
<Your Auth0 Client ID>
¥Client ID:
<Your Auth0 Client ID>
客户秘密:
<Your Auth0 Client Secret>
¥Client Secret:
<Your Auth0 Client Secret>
子域名:
<Your Auth0 tenant url>
,例如下面 url 中粗体部分:https://my-tenant.eu.auth0.com/¥Subdomain:
<Your Auth0 tenant url>
, example it is the part in bold in the following url: https://my-tenant.eu.auth0.com/前端应用的重定向 URL:
http://localhost:3000/connect/auth0
¥The redirect URL to your front-end app:
http://localhost:3000/connect/auth0
使用 ngrok
Patreon 不接受 localhost
网址。
使用 ngrok
为后端应用提供服务。
¥Patreon does not accept localhost
urls.
Use ngrok
to serve the backend app.
ngrok http 1337
不要忘记使用生成的 ngrok URL 更新 Strapi 配置文件 ./config/server.js
中的服务器 URL 和前端应用中的服务器 URL(如果使用 React 登录示例应用,则为环境变量 REACT_APP_BACKEND_URL
)。
¥Don't forget to update the server url in the Strapi 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.
Patreon 配置
你必须是 Patreon Creator 才能注册 Oauth 客户端。
¥You must be a Patreon Creator in order to register an Oauth client.
¥Go to the Patreon developer portal
点击 客户端和 API 密钥
¥Click on Clients & API Keys
点击 "创建客户端"
¥Click on "Create Client"
输入你的组织和网站的详细信息。
¥Enter the details of your organization and website.
"应用类别" 有一个下拉菜单,但没有解释不同类别的含义。"社区" 似乎工作正常。
¥There is a drop-down for "App Category" but no explanation of what the different categories mean. "Community" seems to work fine.
你可以选择 API 的版本 1 或版本 2 - 两者都没有积极开发。版本 2 可能是最好的选择。有关更多详细信息,请参阅他们的 开发者文档。
¥You can choose either version 1 or version 2 of the API - neither are actively developed. Version 2 is probably the best choice. See their developer docs for more detail.
在 "重定向 URI" 下输入
https://your-site.com/api/connect/patreon/callback
¥Under "Redirect URI's" enter
https://your-site.com/api/connect/patreon/callback
保存客户端详细信息,然后你将看到客户端 ID 和客户端密钥。
¥Save the client details and you will then see the Client ID and Client Secret.
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Patreon 提供商
¥Click on the Patreon provider
填写信息:
¥Fill the information:
使能够:
ON
¥Enable:
ON
客户编号:
<Your Patreon Client ID>
- 如上¥Client ID:
<Your Patreon Client ID>
- as above客户秘密:
<Your Patreon Client Secret>
- 如上¥Client Secret:
<Your Patreon Client Secret>
- as above
使用 ngrok
Keycloak 接受 localhost
url。
不需要使用 ngrok
。
¥Keycloak accepts the localhost
urls.
The use of ngrok
is not needed.
Keycloak 配置
访问你的 Keycloak 管理仪表板
¥Visit your Keycloak admin dashboard
如果你还没有字段,你需要创建一个字段
¥If you don't already have a realm, you'll want to create one
在你字段的“客户端”部分中,创建一个新客户端
¥In the Clients section of your realm, create a new client
在功能配置下,确保将
Client Authentication
设置为打开,以确保你可以创建私钥¥Under the capability config, ensure you set
Client Authentication
to on to ensure you can create a private key在访问设置下,确保设置以下值:
¥Under the access settings, ensure you set the following values:
有效的重定向 URI:
http://localhost:1337/api/connect/keycloak/callback
和http://localhost:1337/api/connect/keycloak
¥Valid redirect URIs:
http://localhost:1337/api/connect/keycloak/callback
andhttp://localhost:1337/api/connect/keycloak
允许的 Web 来源:
http://localhost:3000
和http://localhost:1337
¥Allowed Web Origins:
http://localhost:3000
andhttp://localhost:1337
在“客户端范围”部分中,确保将
email
和profile
范围设置为默认值¥In the Client Scopes section, ensure you have the
email
andprofile
scopes set to default在“客户端范围”部分中,确保将
openid
范围设置为默认值,如果没有,则需要在全局客户端范围中手动创建它¥In the Client Scopes section, ensure you have the
openid
scope set to default, if you don't have this you will need to manually create it in the global Client Scopes
表带配置
访问用户权限提供商设置页面
http://localhost:1337/admin/settings/users-permissions/providers¥Visit the User Permissions provider settings page
http://localhost:1337/admin/settings/users-permissions/providers单击 Keycloak 提供商
¥Click on the Keycloak provider
填写信息:
¥Fill the information:
使能够:
ON
¥Enable:
ON
客户编号:
<Your Keycloak Client ID>
¥Client ID:
<Your Keycloak Client ID>
客户秘密:
<Your Keycloak Client Secret>
¥Client Secret:
<Your Keycloak Client Secret>
子域名:
<Your Keycloak realm url>
,例如keycloak.example.com/realms/strapitest
或keycloak.example.com/auth/realms/strapitest
,前面不带协议¥Subdomain:
<Your Keycloak realm url>
, example is eitherkeycloak.example.com/realms/strapitest
orkeycloak.example.com/auth/realms/strapitest
without the protocol before it前端应用的重定向 URL:
http://localhost:3000/connect/keycloak/redirect
¥The redirect URL to your front-end app:
http://localhost:3000/connect/keycloak/redirect
(可选)如果你有自定义 JWKS URL,请设置 JWKS URL,例如
https://keycloak.example.com/auth/realms/strapitest/protocol/openid-connect/certs
¥(Optional) Set the JWKS URL if you have a custom JWKS URL, example is like
https://keycloak.example.com/auth/realms/strapitest/protocol/openid-connect/certs
你的配置已完成。启动后端和 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:
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 theaccess_token
param and that have to requestSTRAPI_BACKEND_URL/api/auth/${provider}/callback
with theaccess_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 atsrc/config.js
.
你无法访问你的管理面板:这很可能是因为你使用带有 ngrok url 设置的后端 url 构建它,并且你停止/重新启动了 ngrok。你需要将后端 url 替换为新的 ngrok url,并再次运行
yarn build
或npm 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
ornpm run build
again.
重设密码
¥Reset password
仅适用于使用电子邮件提供者注册的用户。
¥Can only be used for users registered using the email provider.
- Forgot & Reset flow
- Change the password flow
假设的一般流程:
¥The assumed general flow:
用户转到你忘记密码的页面。
¥The user goes to your forgotten password page.
用户输入他们的电子邮件地址。
¥The user enters their email address.
你忘记密码的页面会向后端发送请求,以向用户发送包含重置密码链接的电子邮件。
¥Your forgotten password page sends a request to the backend to send an email with the reset password link to the user.
用户收到电子邮件并单击特殊链接。
¥The user receives the email and clicks on the special link.
该链接会将用户重定向到你的重置密码页面。
¥The link redirects the user to your reset password page.
用户输入新密码。
¥The user enters their new password.
重置密码页面向后端发送包含新密码的请求。
¥The reset password page sends a request to the backend with the new password.
如果请求包含步骤 3 链接中包含的代码,则密码将被更新。
¥If the request contains the code contained in the link at step 3, the password is updated.
用户可以使用新密码登录。
¥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);
});
你还可以通过 /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 上下文中的用户对象
¥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.
- JavaScript
- TypeScript
module.exports = {
jwtSecret: process.env.SOME_ENV_VAR,
};
export default {
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:
如果你需要配置自定义处理程序以接受其他 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.
// ... 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:
// ... 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
},
},
},
},