Authenticated Requests to Strapi

Written by Sujay Prabhu on April 21, 2022; tagged under Strapi

This blog covers how to make requests to Strapi endpoints as an authenticated user in Strapi v3 & v4.

Before starting, I have created Employees collection type and added some employees.

With Strapi v3

// Request

curl --request GET 'http://localhost:1337/employees'

// Response

{
    "statusCode": 403,
    "error": "Forbidden",
    "message": "Forbidden"
}
Settings -> Users & Permissions plugin -> Roles -> Authenticated -> Employees -> find
// 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"
    }
}

// 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"
    }
]

With Strapi v4

In Strapi v4, they have added another way to get the restricted content.

Note: In Strapi v4, endpoint is changed to `localhost:1337/api/employees`
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
        }
    }
}
If you have any questions or feedback, feel free to drop us a mail at team@codemancers.com.