Authentication and user management are important factors of every user-centric backend application, including Strapi, where different users may have different roles and permissions.
Proper authentication and access control systems are as important as the product itself because it builds trust in the users, knowing that their data is safe.
This article will explain the different authentication and authorization systems available with a walk-through on the most popular ones.
We will also cover the different authentication and authorization systems available in Strapi, learn how to create roles and permissions, authenticate a user, and assign roles to individual users.
We will also explore JWT tokens, how to authenticate a Strapi user with a JWT token, and authorize a user’s request.
Let’s take a look at this beginner’s guide to authentication and authorization:
The ability to validate and verify a user to be who they claim to be is authentication. Countless ways to validate a user in any system are developed, and different factors are created depending on the type of application.
Over time, different validating methods were developed, and different factors were created depending on the system. Yet, the most popular and notable authentication method is the Passwords and Username/Email.
As stated above, there are countless ways to authenticate a user using any of these methods.
These different methods can be further divided into factors of authentication:
You can learn more about authentication using the following:
Strapi uses password-based authentication to create the admin user and, subsequently, other types of users.
Authorization is the process of permitting users to access a particular resource and determining if a specific user has the right permission or role to access a specific route or resources.
There are many authorization methods; I’ll list the most popular ones in this section.
You can gain more insight into authorization here.
Strapi uses JWT Tokens for authorization, which we are going to explore in the article.
Strapi offers authentication and authorization features:
Strapi helps you manage user access and protect your application's resources. For instance, you can build a real estate app with authentication using Strapi's robust features.
In this section, we will explore how authentication and authorization work in Strapi and how you can get started setting up your process. Strapi uses a token-based authentication to authenticate its user by providing a JWT token to a user on a successful password login.
To authenticate a user using the token-based authentication with JWT, a user must log in with the correct credentials so that Strapi can generate a JWT token to authenticate the other request.
The following video runs through the basics of authentication in the Strapi. It is also a great start to get familiar with Strapi V4.
You can authenticate a user by sending a POST request to the auth/local
endpoint.
1import axios from "axios";
2axios
3 .post("http://localhost:1337/auth/local", {
4 identifier: "test@test.com",
5 password: "Password",
6 })
7 .then((response) => {
8 console.log("User profile", response.data.user);
9 console.log("User token", response.data.jwt);
10 })
11 .catch((error) => {
12 console.log("An error occurred:", error.response);
13 });
A user can log in as a reader, regular user, or admin. More users can be created with different permissions and role levels. You can go through how to create a user.
Strapi also provides OAuth and OAuth2 providers to integrate authentication in your application easily. It is a great feature from Strapi, which allows you to impersonate a user in your application and act as the user to perform the queries and tasks as an authenticated user.
You can learn the authentication flow and how to implement the OAuth provider here.
Let’s look at creating a user in Strapi before discussing the different permissions and roles that can be assigned to the user.
To create a user in Strapi, log in as the admin and click on the Content Manager → User tab → Create a user → and fill out the following fields, as shown in the image below.
Also, you can create a new default user by sending a POST request to the auth/local/register
endpoint.
1import axios from "axios";
2axios
3 .post("http://localhost:1337/auth/local/register", {
4 username: "Kapman",
5 email: "test@test.com",
6 password: "Password",
7 })
8 .then((response) => {
9 console.log("User profile", response.data.user);
10 console.log("User token", response.data.jwt);
11 })
12 .catch((error) => {
13 console.log("An error occurred:", error.response);
14 });
Note: The response returns a JWT token that can be accessed.
Once you have logged in successfully and accessed your generated JWT token, you can access any resource, provided you have the right permission and role.
In the example below, let’s look at how to access the articles endpoint with your generated JWT token.
1import axios from "axios";
2
3const { data } = await axios.get("http://localhost:1337/articles", {
4 headers: {
5 Authorization:
6 "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTc2OTM4MTUwLCJleHAiOjE1Nzk1MzAxNTB9.UgsjjXkAZ-anD257BF7y1hbjuY3ogNceKfTAQtzDEsU",
7 },
8});
9
10console.log(data);
In every request, you must add the JWT token with an Authorization
header to be accessible and processed by Strapi.
In section will explain how authorization works in Strapi and how you can get started setting up your process.
The Strapi Permission and User plugin allows you to protect your API with full authentication. It also comes with an ACL strategy that enables you to manage the permissions between user groups.
With the plugin installed, you can add an access layer of verification to your application to check if your request comes with a JWT token within the authorization
header and ascertain that the user has the right permission to access the resources.
Strapi has created a list of roles we can use without creating any roles from the dashboard.
Public Role
When a request is sent to your application without any authorization
header present in the request, the Strapi CMS defaults to using the public role for the request. The common endpoints are available in this role id, including the find
and findOne
endpoints to access data, which would be displayed in the frontend.
Authenticated Role When an authenticated user sends a request without any predefined role assigned to the user during creation, the request automatically defaults to the authenticated role. You can customize the different routes and resources that this role can access.
You can easily update this role by going to the user's advanced settings
and updating the user's default role.
Creating a new custom role for each user is simple with the Strapi Admin dashboard. Once you are logged in as Admin, go to Settings → Click on Roles under “Users & Permissions” → Click on “Add Role” and fill out the fields on Roles under the “Users and Permissions” tab → Click on “Add new role” and fill out the fields provided.
Also, you can select the different permissions that the users under these Roles will perform or have access to.
To assign custom roles to users, go to Settings -> Advanced Settings -> Default Role for Authenticated Users -> select the Custom Roles.
You can also assign roles to an individual or a specific user by going to Users -> Create a user -> fill out the information -> select the specific role for the user under Role.
You can restrict users from any role and permission by simply editing the user and restricting or removing that particular role from the said user. It can be achieved by following the same approach to adding a new user.
In Strapi v4, the Content API and the Admin API are now separated; hence, introducing a new API Tokens feature. Using API tokens allows executing a request to the Content API endpoints as an authenticated user.
It is useful when you want to give access to people or applications without managing a user account or changing anything in the user roles and permission.
Administrators can manage API tokens through the Settings → Global settings → API Tokens sub-section of the settings interface.
To create a new API Token, click on the “Add Entry” button at the top right corner of the page.
The Name field is a human-readable identifier for the token and the Description is an optional field. The Token Type defines the access type to the resources/collections in Strapi. They include "Full access", "Custom", and "Read-only". The token duration is required and set to 7 days, 30 days, 90 days or unlimited.
NOTE: API Tokens are permanent, can be viewed only once, and cannot be regenerated. The token must be deleted to revoke access.
As discussed earlier, when making an authenticated request to Strapi, the Authorization header should be included. When performing a request instead of using the JWT token, the API Token should be used.
1import axios from "axios";
2
3const { data } = await axios.get("http://localhost:1337/articles", {
4 headers: {
5 Authorization: "Bearer <API TOKEN>",
6 },
7});
Follow best practices to secure your Strapi application.
For frontend applications, consider following Next.js authentication best practices to ensure security.
By following these practices, you'll improve your application's security.
By implementing authentication and authorization in Strapi, you enhance your application's security and manage users effectively. Find the plan for your business needs, and experience high performance and flexibility with our headless CMS solutions.
Software Engineer. Community Builder. Indie Hacker