Search code examples
laravelbearer-tokenlaravel-jetstream

How do I get a token (bearer) to run queries and where do I store it?


How do I get a token (bearer) to run queries and where do I store it?

If I use createToken('token')->plainTextToken, I need to store it somewhere.

It is needed to send requests to the API connected as a separate package in the application with its routes.

The only workable solution was this:

Http::macro('test', function () {
    return Http::withHeaders([
        'Accept' => 'application/vnd.api+json',
        'Content-Type' => 'application/vnd.api+json',
    ])->withToken(Auth::user()->createToken('token')->plainTextToken);
});

But I understand that generating a token for every request is weird at the very least, so I'm looking for the right solution.

As I understand it needs to be generated at login and somehow saved.

I use Laravel JetStream (InertiaJS).

P.S: Example request from the controller

$laboratory = Http::test()->get(config('app.url') . $this->api_path . '/laboratories/' . $id);

return Inertia::render('Laboratories/Show', ['laboratory' => $laboratory['data']]);

Solution

  • If you use Laravel Jetstream with Inertia.js/Breeze it will automatically do any authorization for you.

    Mainly when storing bearer token, you store it in cookies, and depending on your javascript framework for example in VueJS you need to use Vuex to store it in a state to access it across components and put it in the Authorization header on every request to run a query if the route has an auth middleware.