Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refresh the laravel_token on API calls with Passport

I created an SPA with Laravel 5.6, Vue 2.5 and Laravel Passport which is working quite well. I really love Laravel and Vue as they make building SPAs with APIs very easy and a lot of fun.

After setting up Laravel Passport as described in the docs the login as well as calls to the API are working as expected based on the 'laravel_token' which is correctly returned and stored in the cookie.

However, my problem is that my users are using the app for a pretty long time, without reloading the page but only performing calls against the API with axios. Somehow Laravel does not refresh the 'laravel_token' (and the corresponding cookie) in API calls (it does so, when I call a 'web' route). Consequently, the 'laravel_token' expires t some point and the user needs to log in again.

How can I force Laravel to refresh the 'laravel_token' (and thereby prolong its validity) with every call of an API route from axios?

Any help is very much appreciated!

like image 918
Matthias Avatar asked Mar 17 '18 21:03

Matthias


1 Answers

I solved a similar issues in the past by creating a simple route (in the web middleware group) to keep the session alive for as long as the browser tab is open.

In routes/web.php:

Route::get('/keep-alive', function () {
    return response()->json(['ok' => true]);
})->middleware('auth');

And then ping this route periodically with javascript:

setInterval(() => {
    axios.get('/keep-alive')
        .then(() => {})
        .catch(() => {})
}, 600000)

I go into a little more detail here: https://stackoverflow.com/a/57290268/6038111

like image 180
Travis Britz Avatar answered Oct 09 '22 12:10

Travis Britz