Any updates to this? I am in the same boat as you. Thanks!
Laravel Sanctum 401 Unauthorized in production only
Hey there!
I'm using Laravel 7 and the SPA authentication variant of Laravel Sanctum (CSRF tokens).
I've managed to make it work locally but when I login on my production site, any requests on my API route will result in 401 Unauthorized.
The funny thing is, that the login route authenticates me. There is no issue with that.
Also I checked, if my website or domain is stateful. (dump & and die in EnsureFrontendRequestsAreStateful class). Yes, it is stateful.
Let's assume for my configurations, that my domain is the following: mydomain.mycompany.dev
Login Logic
public function login(Request $request)
{
$request->validate([
'email' => 'required|string',
'password' => 'required|string',
]);
$isAuthenticated = Auth::attempt([
'us_email' => $request->email,
'password' => $request->password
], $request->filled('remember'));
if ($isAuthenticated) {
$request->session()->regenerate();
return new Response('', 200);
}
return new Response('Unauthenticated', 401);
}
My configurations
env
SANCTUM_STATEFUL_DOMAINS=mydomain.mycompany.dev,localhost,127.0.0.1
SESSION_DOMAIN=mydomain.mycompany.dev
SESSION_DRIVER=cookie
SESSION_LIFETIME=120
session.php
'domain' => env('SESSION_DOMAIN', null),
'secure' => env('SESSION_SECURE_COOKIE'),
'http_only' => true,
'same_site' => 'lax',
sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS')),
'expiration' => null
'middleware' => [
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
],
If this is somehow relevant, the website uses the HTTPS protocol.
This has been included in the Kernel.php file too
use Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful;
(CORS is configured aswell!)
My question is: Why does it work locally but not on my production site?
Thanks for any help!
Please or to participate in this conversation.