DEV Community

Cover image for A Beginner's Guide to Authentication and Authorization in Strapi
Shada for Strapi

Posted on • Originally published at strapi.io

A Beginner's Guide to Authentication and Authorization in Strapi

Author: Mithushan Jalangan

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.

Goals

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.

Prerequisites

  1. Basic understanding of JavaScript
  2. Basic understanding of Strapi—get started here
  3. A Strapi development instance

Let’s take a look at this beginner’s guide to authentication and authorization:

  1. What is authentication?
    • Popular authentication methods
  2. What is authorization?
    • Popular authorization methods
  3. Exploring different authentication methods supported by Strapi
  4. Authenticating a Strapi User using JWT
    • Sending requests as an authenticated user
  5. A detailed overview of authorization methods in Strapi
    • Creating different roles and permissions
    • Assigning different roles and permissions to users
    • Managing roles and permissions
    • Restricting authenticated users based on roles and permissions.
  6. Conclusion

What is Authentication?

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.

Popular Authentication Methods

As stated above, there are countless ways to authenticate a user using any of these methods.

  1. Password-based authentication
  2. Passwordless authentication
  3. Social authentication

These different methods can be further divided into factors of authentication:

  1. Single-factor authentication
  2. Two-factor authentication
  3. Multi-factor authentication

You can learn more about the Authentication of the Auth0 blog.

Strapi uses password-based authentication to create the admin user and, subsequently, other types of users.

What is Authorization?

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.

Popular Authorization methods
There are many authorization methods; I’ll list the most popular ones in this section.

  1. API Keys
  2. Basic Auth
  3. OAuth 2.0
  4. HMAC

You can gain more insight into authorization here.

Strapi uses JWT Tokens for authorization, which we are going to explore in the article.

Exploring Different Authentication Methods Supported by Strapi

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.

Authenticate a Strapi User Using JWT

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.

https://www.youtube.com/watch?v=vcopLqUq594&&t=4336s

You can authenticate a user by sending a POST request to the auth/local endpoint.

    import axios from 'axios';
    axios
      .post('http://localhost:1337/auth/local', {
        identifier: 'test@test.com',
        password: 'Password',
      })
      .then(response => {
        console.log('User profile', response.data.user);
        console.log('User token', response.data.jwt);
      })
      .catch(error => {
        console.log('An error occurred:', error.response);
      });
Enter fullscreen mode Exit fullscreen mode

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.

A screenshot of the Strapi dashboard

Also, you can create a new default user by sending a POST request to the auth/local/register endpoint.

    import axios from 'axios';
    axios
      .post('http://localhost:1337/auth/local/register', {
        username: 'Kapman',
        email: 'test@test.com',
        password: 'Password',
      })
      .then(response => {
        console.log('User profile', response.data.user);
        console.log('User token', response.data.jwt);
      })
      .catch(error => {
        console.log('An error occurred:', error.response);
      });
Enter fullscreen mode Exit fullscreen mode

Note: The response returns a JWT token that can be accessed.

Sending Requests as an Authenticated User

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.

    import axios from 'axios';

    const { data } = await axios.get('http://localhost:1337/articles', {
      headers: {
        Authorization:
          'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwiaWF0IjoxNTc2OTM4MTUwLCJleHAiOjE1Nzk1MzAxNTB9.UgsjjXkAZ-anD257BF7y1hbjuY3ogNceKfTAQtzDEsU',
      },
    });

    console.log(data);
Enter fullscreen mode Exit fullscreen mode

In every request, you must add the JWT token with an Authorization header to be accessible and processed by Strapi.

A Detailed Overview of Authorization Methods in 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.

Managing Roles and Permissions

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 system 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 Different Roles and Permissions

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 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.

A screenshot of what your screen should look like during this process

Assigning Different Roles and Permissions to Users

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.

A screenshot of this process

Restricting Authenticated Users Based on Roles and Permissions.

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.

What's New in v4? API Tokens

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 Setting → Global settings → API Tokens sub-section of the settings interface.

See the change in this screenshot

To create a new API Token, click on the “Add Entry” button at the top right corner of the page.

What your screen should look like at this stage

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. By default the token can be either read-only or full access.

A screenshot of the filled fields

What happens when your changes are successfully saved

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.

    import axios from 'axios';

    const { data } = await axios.get('http://localhost:1337/articles', {
      headers: {
        Authorization:
          'Bearer <API TOKEN>',
      },
    });
Enter fullscreen mode Exit fullscreen mode

Conclusion

We have discussed in detail the different authentication and authorization processes available in Strapi, how to authenticate a user and a user’s request, and also how to create and manage different roles and permission.

Top comments (1)

Collapse
 
lilybell profile image
LilyBell

How do you authenticate with a Strapi?
voodoo spells to hurt someone