My app normally uses the web routes with their regular cookie-based authentication, but in some places I need to use AJAX just for convenience (e. g. sending a message without reloading the page). Might think of it as the old Reddit website (at least how it looks like on the surface), when the entire webpage is loaded, but then the requests to post a comment are sent via XHR.
I'm using Sanctum for this, and from the documentation it seems that, for 'SPA authentication', which is probably closer to what I need, I'd first need to make requests to /sanctum/csrf-cookie and /login routes, but, since the user is already logged in and we already have the necessary information for authentication, is that actually necessary now?
I put this together using jQuery, seems like at least the cookie and token were there in the headers, whether they were correct or not:
$.ajax({
url: '/api/tickets/{{$id}}/comment',
method: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: formData,
// I supposed that this one would send the cookie to the server? not sure, but again, at least there's one in the headers
xhrFields: {
withCredentials: true
},
headers: {
'X-CSRF-TOKEN': csrf // this is set before to the csrf token from the form
},
// callbacks shown just for demonstration purposes
success: function(data) {
console.log(data);
},
error: function(xhr, status, exception) {
console.log(xhr); // object with response JSON being only {"message":"Unauthenticated."}
console.log(status); // error
console.log(exception); // Unauthorized
}
});
And the API endpoint just uses the sanctum auth:
Route::middleware('auth:sanctum')
->post('/tickets/{ticket}/comment', [TicketApiController::class, 'comment']);
And, after sending the request (I'm authenticated in the app itself), I only get the 401 error. So, again, is using those two routes the only way, even if the user is already authenticated? Or should it be possible to authenticate API with just the regular authentication and I'm just missing something here?
/api)… although now that you made me think, at least it's supposed to, but I've set up the virtual host name in httpd-vhosts.conf and hosts files before, and my browser was sending that host name too… so, I might try removing the virtual host name and see if that helps