How does your website make ajax calls?
Jan 15, 2024
2
Level 1
API Authentication with Sanctum is confusing me
I try to keep views in the web.php and all requests form pages i want to keep in api.php.
If a user is logged in an click a button i execute an ajax-call to the api but i get back an HTTP-Error 419.
I follow the steps from : Laravel 10 docs /sanctum#spa-authentication , but I reach all the time 419.
Is there something additional to change??
api.php
Route::controller(TokenController::class)->group(function(){
Route::post('v1/radio/token/save')->name('api_radio_token_save');
});
Level 2
you need to ensure that your AJAX requests include the proper CSRF token. Include the token in your Blade views
<meta name="csrf-token" content="{{ csrf_token() }}">
in your AJAX request
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Then in config/sanctum.php, ensure that the stateful configuration is set to use cookies.
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,localhost:3000,localhost:8000,127.0.0.1,127.0.0.1:3000,127.0.0.1:8000')),
Set these ENV properly
SESSION_DOMAIN=.yourdomain.com
SANCTUM_STATEFUL_DOMAINS=.yourdomain.com
2 likes
Please or to participate in this conversation.