Where to store the JWT for authentication when Laravel is used as client?

Viewed 1081

I use Laravel 6 and GuzzleHTTP 7.

I could manage to make a request to an external (REST-) API and successfully authorize and get a token back:

{"access_token":"FooXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MjExNjkyNDQsImlhdCI6MTYxODU3aNzI0NCwibmJmIjoxNjE4NTc3MjQ0LCJpZGVudGl0eSI6MTQzfQ.wdDzVbE-5O8mfsIqzNvXFpv7THkYYp522HMpyEc8LX0BAR"}

Do I have to save this token explicitly in a session? I'm trying to use this token in every following requests to the external API.

By googling I found only tutorials for Laravel how to generate JWT but not how to proceed when Laravel is used as a client and requests JWT.

Any help much appreciated!

UPDATE: The Laravel APP itself is the client (regardless of the user "inside" Laravel).

1 Answers

Upon getting your token from a 3rd party service, store it in some form of storage (e.g. file, database, cache). I recommend using a Cache, as it's faster (if your using an in-memory cache like Redis), and you can set a TTL.

If the token expires after a certain period of time, and doesn't have a refresh token, then set the TTL to that date/time.

Example:

$ttl = Carbon::now()->addHour(); // set to when it expires or null if token doesn't expire
$jwtToken = Cache::remember('fooServiceJwtToken', $ttl, function () {
    $jwt = getJwtTokenUsingGuzzle(); // CHANGE
    return $jwt;
});

Do not store the data in a session, as sessions are tied to users using your application.

Related