Handling Expired Token in Laravel

Handling expired token in Laravel

Update 2022; the csrf_token() method will never create a new token, and it simply loads existing CSRF-token from current-session (if any, and returns it).

But this tricks you into thinking it works, because Laravel increases the life-time of the existing CSRF-token, and that each time a request to a CSRF-protected route is made.

For an implemention that really creates new CSRF-token, see:

stackoverflow.com/Get new CSRF token with Ajax?

Original Answer (From 2015)

A work around for it, is to actually get the new token every certain time, otherwise you are defeating the purpose of the csrf token:

<html>
<head>
<meta name="csrf_token" content="{{ csrf_token() }}">
</head>
<body>
<script type="text/javascript">
var csrfToken = $('[name="csrf_token"]').attr('content');

setInterval(refreshToken, 3600000); // 1 hour

function refreshToken(){
$.get('refresh-csrf').done(function(data){
csrfToken = data; // the new token
});
}

setInterval(refreshToken, 3600000); // 1 hour

</script>
</body>
</html>

In laravel routes

Route::get('refresh-csrf', function(){
return csrf_token();
});

I apologize in case of any syntax errors, haven't used jquery for long time, but i guess you get the idea

Laravel Sanctum: How to configure the expiration date of the token?

You can publish the Laravel configuration:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

See https://laravel.com/docs/8.x/sanctum#installation

After this you are able to change all configuration options in config/sanctum.php. The configuration files in config will overwrite the vendor default configuration.



Related Topics



Leave a reply



Submit