Gatsby with Laravel Sanctum 401 Unauthorized

Viewed 305

I am geting a 401 Unauthorized response.

I followed Laravel Sanctum docs

I'm currently working on localhost for both frontend and backend:

frontend (Gatsby version 2.31): localhost:8001 <- used "npm start"
backend (Laravel version 8.26.1): localhost:8000 <- used "php artisan serve"

Here's what I have setup:

Gatsby: signup.js:

import apiClient from "../utils/api";

const handleSubmit = (e) => {
  e.preventDefault();

  apiClient().get('/sanctum/csrf-cookie').then( () => {   

     apiClient().post("/api/register", {
         firstName: "newfirst",
         lastName: "newlast",
         email: "email@domain.com",
         password: "123456"
     }
     ).then(function (response) {
         if (response.data.error) {
           console.log("Error: ",response.data.error);
         } else {
           console.log("Success");
         }        
     })
     .catch(function (error) {
       console.log(error);
     });
  });
}

Gatsby: util/api.js:

import axios from "axios";

export default function api() {
  const apiClient = axios.create({
     baseURL: "http://localhost:8000",
     withCredentials: true
  });
  return apiClient;
}

Laravel 8:
Installed Sanctum by following Laravel Sanctum installation

.env

SESSION_DRIVER=cookie
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8001 // <- from what I understand, this should point to the frontend

config/cors.php

'paths' => ['api/*', 'sanctum/csrf-cookie'],
'supports_credentials' => true,

app/Http/Kernel.php

use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;

protected $middlewareGroups = [
    'web' => [...],
    'api' => [
        EnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
];

config/sanctum.php

'stateful' => explode(',', env(
    'SANCTUM_STATEFUL_DOMAINS', 
    'localhost,localhost:3000,127.0.0.1,127.0.0.1:800,::1,localhost:8000'
)),

no changes in config/sanctum.php as SANCTUM_STATEFUL_DOMAINS can be entered in .env file

routes/api.php

Route::post("register", [AuthController::class, "register"])->middleware("auth:sanctum");

app/Http/Controllers/AuthControllers.php

public function register(Request $request) {

    $this->validator($request->all())->validate();
    $user = $this->create($request->all());
    return response()->json([
        'user' => $user,
        'message' => 'registration successful'
    ], 200);

}

config/auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'sanctum', //<- I also updated this from "token" to "sanctum"
        'provider' => 'users',
        'hash' => false,
    ],
],

Solutions I tried:

adding "header" to api call in Gatsy > signup.js:

apiClient().get('/sanctum/csrf-cookie').then( () => {   

  const token = Cookies.get("XSRF-TOKEN"); //<- npm install js-cookie
  
  apiClient().post("/api/register", {
      firstName: "newfirst",
      lastName: "newlast",
      email: "email@domain.com",
      password: "123456"
    }, {
      headers: {
        "Authorization": "Bearer "+ token //<- added this part
      }
    }
  ).then(function (response) {

also this in "header"

apiClient().get('/sanctum/csrf-cookie').then( () => {   

  const token = Cookies.get("XSRF-TOKEN");
  
  apiClient().post("/api/register", {
      firstName: "newfirst",
      lastName: "newlast",
      email: "email@domain.com",
      password: "123456"
    }, {
      headers: {
        "X-XSRF-TOKEN": token //<- "X-XSRF-TOKEN" instead of "Authorization"
      }
    }
  ).then(function (response) {

confirmed that "XSRF-TOKEN" was created after "sanctum/csrf-cookie" request:

XSRF-TOKEN created:

Still getting "401 (Unauthorized)"
enter image description here

Thank you in advance

1 Answers

Helllo!

The ‘auth:sanctum’ middleware is used to protect endpoints against unauthenticated users.

So you should remove it from the register route as you are basically asking the user to authenticate themselves before registering an account.

Related