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
- Lets try to fetch employee details by making a GET request
- As collections are restricted by default, it cannot be accessed as a Public user resulting in
403
status code. - To get rid of the
Forbidden
error, lets add permission to/employees
endpoint by enabling:
Settings -> Users & Permissions plugin -> Roles -> Authenticated -> Employees -> find
- A JWT token should be added to API request to fetch data from restricted endpoints
- To get the JWT token, create a user and get the user authenticated.
- Now, add the JWT token obtained in last step to our first step request's Authorization header
With Strapi v4
In Strapi v4, they have added another way to get the restricted content.
- First way is same as the v3's, based on roles and Permissions.
- This approach can be followed when the requirement is to restrict contents based on roles.
- Learn more about authenticated requests to Strapi by assigning permissions to roles here
Note: In Strapi v4, endpoint is changed to `localhost:1337/api/employees`
- Second way is by making use of API tokens, which is a built-in feature in Strapi v4.
- This allows executing request on restricted endpoints as an authenticated user without the hassle of roles and permissions.
- To generate API tokens, click on
Settings -> API tokens -> Create new token
- Copy the token generated and add it to request's Authorization header
- Learn more about making authenticated requests to Strapi using API tokens here