Laravel 9 Sanctum (with cookies) error 401 after successful login SPA React

514 Views Asked by At

I am building the authentication of a SPA in React with Laravel 9 Sanctum. I have my SPA at https://agefa.devetapia.cl and the server at https://backend.devetapia.cl. I am authenticating using cookies (not token) and everything is fine until login. After the successful login I try to make a request and it gives me a 401 error that I am not authenticated. I have read a lot of documentation and I think that I have the error in the domains and subdomains. I have tried many different ways. All the tutorials and videos are with localhost with ports, but it is not my case.

My domains are https.

My cors.php file:

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

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

My config/sanctum.php:

    'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
        '%s%s',
        'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
        Sanctum::currentApplicationUrlWithPort()
    ))),

My .env

SESSION_DRIVER=cookie
SESSION_DOMAIN=.devetapia.cl
SANCTUM_STATEFUL_DOMAINS=devetapia.cl

My config/session.php

'domain' => env('SESSION_DOMAIN'),

My routes/api.php:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

use App\Http\Controllers\LoginController;

Route::post('login', [LoginController::class, 'login']);

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
        return response()->json(['status' => true, 'user' => auth()->user()]);
});

my axios setup in react:

import axios from 'axios';
 
const apiClient = axios.create({
    baseURL: 'https://backend.devetapia.cl',
    withCredentials: true,
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json'
    },
});
 
export default apiClient;

and the call from React:

   async function getUser()  {

        const csrf = await apiClient.get('/sanctum/csrf-cookie');
         
        const login = await apiClient.post('/api/login', {
            email: '[email protected]',
            password: 'clavesecreta',
        }).then(response => {
                if(response.data.user) {
                    console.log('login=', response.data.user.name);
                }
            }).catch(error => {
                console.log(error.response.data.message);
            });
            
        const user = await apiClient.get('/api/user');
   
        console.log('user= ', user);
    }

The 401 error gives me when I do:

const user = await apiClient.get('/api/user');

even though the login was successful.

It seems to me that the problem is the definition in the .env of SESSION_DOMAIN and SANCTUM_STATEFUL_DOMAINS but I have not been able to find the correct configuration.

0

There are 0 best solutions below