So I'm using Jetstream for the authorization part! Now I want to use Laravel sanctum's "auth:sanctum" middleware to protect my api's!
But when I call the api from my SPA, it gives me "401 (Unauthorized)" error even though I'm making csrf-cookie while logging in!
The api works fine when I call it from Postman by passing the token in Bearer token header!
My codes:
Login.vue: (This is where I'm creating the token)
axios.get('/sanctum/csrf-cookie')
.then(response => {
this.form
.transform(data => ({
... data,
remember: this.form.remember ? 'on' : ''
}))
.post(this.route('login'), {
onFinish: () => this.form.reset('password'),
})
})
AppLayout.vue: (This is where I'm calling the api)
axios.get('/api/abilities',)
.then((response)=>{
console.log(response.data);
})
.catch((error)=>{
console.log(error);
})
api.php:
Route::middleware('auth:sanctum')->get('/abilities', function (Request $request) {
return auth()->user();
});
Other things that I've already done are:
- Added "axios.defaults.withCredentials = true;" to bootstrap.js
- Added "SANCTUM_STATEFUL_DOMAINS=localhost:8000;" to .env file
- Added "EnsureFrontendRequestsAreStateful::class" to Kernel.php