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
How to Detect an Incoming Request (With PHP Script) from a Cname Subdomain
How to Redirect Stdout to a File in PHP
How to Set Default Value for Form Field in Symfony2
Are There Limits for Session Variables
Curl , Get Redirect Url to a Variable
How to Remove Square Brackets and Anything Between Them with a Regex
Laravel 5.3 Auth Check in Constructor Returning False
PHP - Session Destroy After Closing Browser
Passing PHP Variable from Controller to JavaScript Function in the Head of a View
How to Get Customer Details from an Order in Woocommerce
How to Replace Part of a String in PHP
Add a Prefix to Each Item of a PHP Array
How to Send Cookies Using PHP Curl in Addition to Curlopt_Cookiefile