tomasosho's avatar

401 Unauthorized using axios and sanctum React js

My sanctum has been setup correctly. My Login and Registration work correctly. But when i try retrieving user details guarded by santum middleware from api i get 401 Unauthorized using axios and sanctum.

apiClient.get("/sanctum/csrf-cookie").then((response) => {
      apiClient
      .post('/api/logout', 
        {
          headers: {
            Authorization : `Bearer ${token}`
          }
        }
      // { Authorization: `Bearer ${token}` }
      )
    .then(() => {
        //successful response    })
	}
0 likes
13 replies
vincent15000's avatar

Retrieving the CSRF token is just required for the first time when you connect to the app.

Once your are connected, you just have to send your request (without retrieving the CSRF token).

apiClient
    .post('/api/logout', 
    {
    	headers: {
            Authorization : `Bearer ${token}`
        }
     })
    .then(() => {
        //successful response
	})
tomasosho's avatar

@vincent15000 Still getting same error

const useToken = JSON.parse(localStorage.getItem('token')) || '';

onst logout = (e) => {
    e.preventDefault()
    
    apiClient.get("/sanctum/csrf-cookie").then((response) => {
      apiClient
      .post('/api/logout', 
      {
        headers: {
              Authorization : `Bearer ${useToken}`
          }
       })
    .then(() => {
      console.log('000ssss')
      //successful response
      localStorage.removeItem('userName')
      localStorage.removeItem('userEmail')
      localStorage.removeItem('userLoggedIn')
      navigate(`/`);
    })
}

I can login and register but i can't get data or post data once i use ['middleware' => ['auth:sanctum']

1 like
tomasosho's avatar

It works well with postman, but on react js it doesn't.

1 like
tomasosho's avatar

@MohamedTammam I was wondering about that because i wasn't getting any session returned

Route::group(['middleware' => ['auth:sanctum']], function () {
    Route::post('/logout', [AuthController::class, 'logout']);
    Route::get('/profile', [AuthController::class, 'profile']);
});

This is what i have and it should work with the front end, since it already works using Postman

Front End React JS
const useToken = JSON.parse(localStorage.getItem('token')) || '';
const headers = {
    accept: 'application/json',
    Authorization: 'Bearer ' + useToken.token
  }

const logout = (e) => {
    e.preventDefault()
    
      apiClient
      .post('/api/logout', 
      {
        headers: headers
      })
    .then(() => {
      console.log('000ssss')
      //successful response
      localStorage.removeItem('userName')
      localStorage.removeItem('userEmail')
      localStorage.removeItem('userLoggedIn')
      navigate(`/`);
    })
}
1 like
tomasosho's avatar

@MohamedTammam I'm running both the front and back end on local host my .env is set as

SESSION_DRIVER=cookie
SESSION_DOMAIN=.127.0.0.1:8000
# backend-app
SANCTUM_STATEFUL_DOMAINS=http://localhost:3000
# front-end-spa
1 like
tomasosho's avatar

@MohamedTammam They are both on localhost served over different ports

import axios from 'axios';

const apiClient = axios.create({
    baseURL: 'http://127.0.0.1:8000',
    headers: {
      'X-Requested-With': 'XMLHttpRequest'
    },
      withCredentials: true,
  });

export default apiClient;
1 like
vincent15000's avatar

@tomasosho You should first choose between token and session authentication.

If you choose token authentication, then forget the session and concentrate over the token problem.

If you choose session authentication, then forget the token and concentrate over the session problem.

If you are on the same domain and that you can't send any request, it's probably a session problem. So you should check your .env file and/or your sanctum configuration file.

tomasosho's avatar

@vincent15000 I'm able to send requests on login and registration it's when i need to get or post data to and from the api that is guarded by auth:sanctum that i get the 401 Error even after including Bearer Token const headers = { accept: 'application/json', Authorization: 'Bearer ' + useToken.token }

tomasosho's avatar

@vincent15000 my console.log(headers)

{accept: 'application/json', Authorization: 'Bearer 21|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'}

Please or to participate in this conversation.