Laravel Csrf Token Expiration Time

Laravel CSRF Token Expiration Time

In Laravel, CSRF (Cross-Site Request Forgery) protection is provided by generating and validating a CSRF token on each form submission. The CSRF token helps to prevent unauthorized requests and protects your application against CSRF attacks.

The expiration time for the CSRF token in Laravel is controlled by the “csrf_expire” configuration option in the “config/session.php” file. By default, it is set to 120 minutes (2 hours).

If a user stays inactive on your website for longer than the CSRF token expiration time, the token will expire. This means that any subsequent form submissions will fail validation due to an expired token.

Example:

Let’s say you have a Laravel form with CSRF token:

“`html

@csrf


“`

When the user submits this form, Laravel validates the CSRF token. If the token is expired (based on the expiration time), Laravel will throw a “TokenMismatchException” error.

To avoid CSRF token expiration issues, you can either:

  • Keep the user session active by preventing session expiry (e.g., by increasing session lifetime or adding activities to keep the session alive).
  • Implement refreshing the CSRF token on each page load or AJAX requests. This way, the token will always be valid, even if the user session expires.

You can refresh the CSRF token using JavaScript and update it in the form:

“`javascript
// Refresh CSRF token
function refreshCsrfToken() {
axios.get(‘/refresh-csrf-token’).then(response => {
const newToken = response.data.csrfToken;
document.querySelector(‘input[name=”_token”]’).value = newToken;
}).catch(error => {
console.error(‘Failed to refresh CSRF token’, error);
});
}

// Call refresh function on page load
window.addEventListener(‘load’, refreshCsrfToken);
“`

The above example assumes you have an API endpoint (“/refresh-csrf-token”) in your Laravel application that returns a new CSRF token for each request.

By refreshing the CSRF token on each page load or AJAX request, you ensure that the token is always up-to-date and valid, regardless of the session expiration time.

Read more interesting post

Leave a comment