Beginners Guide to Authentication & Authorization in Strapi

Authentication and user management are important factors of every user-centric backend application, including Strapi, where different users may have different roles and permissions.


This is a companion discussion topic for the original entry at https://strapi.io/blog/a-beginners-guide-to-authentication-and-authorization-in-strapi

user/pass is visible in request, how it is secure ?

Great content, thanks for sharing :raised_hand:

I needed to add “/api” to the path when registering a new user:

axios
      .post('http://localhost:1337/api/auth/local/register', {
        username: 'xxxxxx',
        email: 'yyyy@zzzz.com',
        password: 'wwwwwww',
      })

hello everyone I wanna know how can I get the user/me data from strapi

The documentation is complicated, plus it doesn’t include /api

You need to make a POST request first, then a unique JWT will populate on each new POST; then use that JWT to GET data from https://api.example.com/api/posts.

the API POST URL: https://api.example.com/api/auth/local

the BODY REQ: identifier test@email.com
the BODY REQ: password test

the API GET URL: https://api.example.com/api/posts
the BEARER TOKEN : exampleiwiaWF0IjoxNjY5ODQ1MTAxLySG5ZMMreMjZQ0

How long does the POST token last? I noticed I am able to reuse that token.

I can’t find any examples using the fetch API.

They all use axios, but in the past I had hidden errors decoding with axios, so I decided not to use it anymore.

I think axios should be optional, not required.

I don’t use Axios either here is my simple example of registering a user. This is from my react application.

  const registerUser = async () => {
    try {
      const response = await fetch('http://localhost:1337/api/auth/local/register', {
        method: 'POST',
        body: JSON.stringify({
          username: 'Strapi user',
          email: 'user@strapi.io',
          password: 'strapiPassword',
        }),
        headers: {
          'Content-Type': 'application/json',
        },
      });
      const data = await response.json();
      console.log('User profile', data.user);
      console.log('User token', data.jwt);
      setUser({
        user: data.user,
        jwt: data.jwt,
      });
    } catch (error) {
      console.log('An error occurred:', error);
    }
  };

I know docs show axios examples only. I am not curious why they chose axios over something like fetch.

1 Like

But I want to know in which file in the strapi application do you write this code of authentication