I have an App created with Laravel with InertiaJS and VueJS. It is set with all the Jetstream scaffolding for the Authentication, everything from the auth is handled by jetstream and inertia.
The problem is that I have a couple of pages that need to call the api.php routes in my project, for example in my Vue.JS page:
fetch(`/api/v1/companies/${this.user.id}`)
.then(response => response.json())
.then(res => {
console.log(res)
});
And this is a simple endpoint in my api.php:
Route::get('/companies/{user_id}', [Controller::class, 'index']);
How can I make this endpoint auth protected, so only authenticated users get access (like with Laravel Sanctum), but in the Inertia environment? Is there a way to put this endpoint behind a middleware and send a token from the Vue.JS page?
2
Answers
So, just in case anyone ends up here with the same problem, I ended up solving this by generating a token by myself in the backend and sending it to the view. I don't think this rises a security problem, but I am no expert.
So what I did was, in the controller:
And send it to the view (or append it to the user). Then, just use it in the view to call an endpoint protected with:
And making a fetch in the view, with the token like @Omar Corrales sugested.
But I think the web route with the first controller must be under the same middleware form auth:sanctum. I hope this helps someone in the future.
If you’re using Sanctum it’s very easy to implement it in your routes.
then you can just call the api like this
Sanctum sends CSRF tokens in requests.
If your application is set up correctly with Sanctum, and the user is authenticated, the CSRF token should already be sent with each request, and you don’t need to manually add the Authorization header.