session cookie not passed on Ajax requests
After enabling this package using the defaults, Livewire still seems to work as expected but custom Javascript calls to fetch no longer pass the session cookie.
Any idea what setting is causing this?
https://developer.mozilla.org/en-US/docs/Web/API/RequestInit#credentials
Please refer to the link above to correctly transmit the cookie.
credentials defaults to same-site but even setting it to include does not fix the issue.
I also tried setting supports_credentials in cors.php to true.
I also tried setting sandbox: allow-same-origin in secure-headers.php to true.
All my Javascript code does it the following:
const response = await fetch(analyticsUrl, {
method: 'GET',
credentials: 'include',
headers: {
'Accept': 'application/json',
'X-App-Locale': '{{ app()->getLocale() }}',
'Access-Control-Allow-Origin': '{{ Request::getHost() }}',
},
});
According to the document at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#including_credentials, when the SameSite attribute of your cookies is set to Strict or Lax, cookies will not be sent even if the credentials are set to include. Please check the SameSite attribute of your website's cookies.
Thank you for your additional insight. It should be noted that the session cookie is from the same domain, so from my understanding this should not be an issue.
So in my api.php I have. These are the endpoints I am calling
Route::middleware(['auth:sanctum'])->group(function () {
Route::get('/user/analytics', [AnalyticsController::class, 'userApi'])
->name('api_user_analytics');
Route::get('/team/analytics', [AnalyticsController::class, 'organizationApi'])
->name('api_team_analytics');
});
In Kernel.php I have:
'api' => [
'ensureStateful',
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
So I am honestly a bit confused why it even is able to authenticate via session cookies right now.
Now if I load the UI without this package enabled and then trigger these API requests, they work fine.
But if I load the UI with the package enabled, they fail with an Unauthenticated. error message.
So I take this to show that the issue is happening on the Javascript side based on the headers we respond with once the package is enabled.
However the session cookie is still passed by the API call when this package is enabled.
I realize I am asking you to debug my application here without access to the code. I can promise that I will submit documentation if we figure this out.
Maybe you could try recreating the issue with a fresh Laravel project. That way, I can help you more accurately.
Close due to inactivity.