Reputation: 28795
From reading the Laravel docs, it appears that when using Sanctum Vue will just use the cookie-based authentication.
I was trying to move an existing app (with login done using Livewire) to Vue, but calls direct to my first api endpoint were redirecting to the login page.
So I created a clean installation of Larvel, installed Breeze (with Inertia), then Sanctum, published the config etc.
But when I login and then visit my test endpoint (which just returns 200 Ok), it redirects to the login page (which, because I am logged in, redirects to the Breeze dashboard).
Do I need to do anything manually for my endpoint, guarded by auth:sanctum
, to pass authentication?
Update
I've set axios.defaults.withCredentials
, and it's returning 401 Unauthorized
. My app.js:
axios.defaults.withCredentials = true;
axios.get('/api/test')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
Upvotes: 1
Views: 2356
Reputation: 5078
First ensure that your application's CORS configuration is returning the Access-Control-Allow-Credentials
header with a value of True
. This may be accomplished by setting the supports_credentials
option within your application's config/cors.php
configuration file to true
.
Then, if you are using axios, you should enable the withCredentials
option on your axios instance:
axios.get('some api url', {withCredentials: true});
or globally:
axios.defaults.withCredentials = true;
If you are not using Axios to make HTTP requests from your frontend, you should perform the equivalent configuration on your own HTTP client.
Laravel Docs Reference.
If you are using Postman to test your api, here is a smart implementation of sanctum authentication requests. Basically you have to get the sanctum cookie first, and then send the cookie on XSRF-TOKEN
header.
Upvotes: 1