skip to Main Content

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


  1. Chosen as BEST ANSWER

    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:

    $user = Auth::user();
    $token = $user->createToken('a secret variable')->plainTextToken;
    

    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:

    Route::middleware('auth:sanctum')->get('/companies/{user_id}', [Controller::class, 'index']);
    

    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.


  2. If you’re using Sanctum it’s very easy to implement it in your routes.

    Route::middleware('auth:sanctum')->get('/companies/{user_id}', [Controller::class, 'index']);
    

    then you can just call the api like this

    fetch(`/api/v1/companies/${this.user.id}`, {
        headers: {
            'Authorization': `Bearer ${this.$page.props.user.token}` // If you need to pass a token explicitly
        }
    })
    .then(response => response.json())
    .then(res => {
        console.log(res)
    });
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search