Skip to main content

strapi用户管理

strapi 的用户有两种,一种是可以登录 cms 后台的管理员用户(administrator-user),还有一种是终端用户(end-user),就是在面向用户的客户端中进行注册登录的用户。

管理员(administrator user)

后台设置管理员用户:Settings/ADMINISTRATION PANEL/,下有 Roles 和 Users,其中 Roles 是后台编辑的管理员账号类型,免费版包括有超级管理员,编辑,作者三个身份。

Users 里可以邀请用户注册为管理员,这里记住不要发给终端用户注册,因为是用来编辑后台配置的管理员。

终端用户(end-user)

后台设置终端用户:Settings/USERS&PERMISSIONS PLUGIN,为啥是 plugin,因为默认带的终端用户是通过插件@strapi/plugin-users-permissions实现的。

所以,也可以自定义插件来实现自己的终端用户管理。

模拟用户注册:

插件要求用户注册必须提供 email 和 password 字段,其他字段都选填。

curl --location --request POST 'http://localhost:1337/api/auth/local/register' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'email=daichangxin@gmail.com' \
--data-urlencode 'password=123456' \
--data-urlencode 'username=dcxin'

返回数据:

{
"jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNjUyMTY3MTY0LCJleHAiOjE2NTQ3NTkxNjR9.A0J6v5rEHMJaSBWIcia_uoLFsgKwK-Cuarh_Kxcq41g",
"user": {
"id": 1,
"username": "dcxin",
"email": "daichangxin@gmail.com",
"provider": "local",
"confirmed": true,
"blocked": false,
"createdAt": "2022-05-10T07:19:24.549Z",
"updatedAt": "2022-05-10T07:19:24.549Z"
}
}

其中 jwt 字段就是该用户访问需授权访问接口时需在 Header 中带的 Authorization 字段值。

模拟登录

curl --location --request POST 'http://localhost:1337/api/auth/local' \
--form 'identifier="daichangxin@gmail.com"' \
--form 'password="123456"'

同样返回 jwt 字段和用户信息。

请求需授权访问的接口

header 中设置 jwt,这里 ListMyPosts 是我自定义的接口,可以自行更改。

curl --location --request POST 'http://localhost:1337/api/post/ListMyPosts' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6NSwiaWF0IjoxNjUxNTU4MjkzLCJleHAiOjE2NTQxNTAyOTN9.PP-zhJ4xIoxNxZX_z3fW-claN4Vm-GrLhlACu2v6HSM'