对Strapi的认证请求
这篇博客涵盖了如何在Strapi v3和v4中以认证用户的身份向Strapi端点发出请求。
在开始之前,我已经创建了Employees集合类型并添加了一些员工。
使用Strapi v3
- 让我们尝试通过发出GET请求来获取雇员的详细信息
// Request
curl --request GET 'http://localhost:1337/employees'
// Response
{
"statusCode": 403,
"error": "Forbidden",
"message": "Forbidden"
}
- 由于集合在默认情况下是受限制的,它不能以公共用户的身份访问,导致
403状态代码。 - 为了摆脱
Forbidden的错误,让我们通过启用来为/employees端点添加权限:
Settings -> Users & Permissions plugin -> Roles -> Authenticated -> Employees -> find
- 为了从受限的端点获取数据,应在API请求中添加JWT令牌。
- 为了获得JWT令牌,创建一个用户并使用户得到认证:
// Request
curl --request POST 'localhost:1337/auth/local' \
--form 'identifier="test@test.com"' \
--form 'password="test@123"'
// Response
{
"jwt": TOKEN,
"user": {
"id": 3,
"username": "test",
"email": "test@test.com",
"provider": "local",
"confirmed": false,
"blocked": false,
"role": {
"id": 1,
"name": "Authenticated",
"description": "Default role given to authenticated user.",
"type": "authenticated"
},
"created_at": "2022-04-21T14:01:32.672Z",
"updated_at": "2022-04-21T14:01:32.679Z"
}
}
- 现在,将上一步获得的JWT令牌添加到我们第一步请求的授权头中:
// Request
curl --request GET 'localhost:1337/employees' \
--header 'Authorization: Bearer TOKEN'
// Response
[
{
"id": 1,
"name": "test",
"age": null,
"published_at": "2022-04-13T06:27:46.430Z",
"created_at": "2022-04-13T06:27:44.423Z",
"updated_at": "2022-04-13T06:27:46.441Z"
}
]
使用Strapi v4
在Strapi v4中,他们增加了另一种获取受限内容的方法:
Note: In Strapi v4, endpoint is changed to `localhost:1337/api/employees`
- 第二种方法是利用API令牌,这是Strapi v4的一个内置功能。
- 这允许在受限的端点上以认证用户的身份执行请求,而不需要角色和权限的麻烦。
- 要生成API令牌,请点击
Settings -> API tokens -> Create new token
- 复制生成的令牌,并将其添加到请求的授权头:
// Request
curl --request GET 'localhost:1337/api/employees' \
--header 'Authorization: Bearer API_TOKEN'
// Response
{
"data": [
{
"id": 1,
"attributes": {
"name": "test",
"age": 50,
"createdAt": "2022-04-18T15:46:02.760Z",
"updatedAt": "2022-04-18T15:46:06.891Z",
"publishedAt": "2022-04-18T15:46:06.887Z"
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 1
}
}
}
- 了解更多关于使用API令牌对Strapi进行认证请求的信息。