Security


Adding CSRF Token

By default, a CSRF token has been set in the meta:csrf-token dynamically in the base layout. This meta csrf token will be sent along with Livewire "AJAX" requests (e.g., lw-get, lw-post, etc.)

To add a CSRF token to a normal HTML form, you need to call the helper service(), passing the Security class and chaining with the set_token_field() inside the form.

<form method="post" action="{{ route('update.user') }}">
 <!-- form fields -->
 {!! service("Zap\Core\Utils\Security")->set_token_field() !!}
</form>

Since Zap includes Litewire by default, you can also load its plugin livewire-auto-csrf-plugin.js. The plugin will automatically add a hidden CSRF token field to the form.

If using XHR or jQuery for sending AJAX requests, add a key (e.g., _token) while the value is a generated token.

data:{
 //other keys
 _token: "{{ service('Zap\Core\Utils\Security')->generate_token() }}"
}

Validating CSRF Token

CSRF tokens are validated in the target controller method. Whether it receives requests from normal HTML form or AJAX/XHR, the method used is validate_request(). Here is an example:

public function updateUsername(Request $request, Security $security) {
 $security::get_instance();
 if(!$security->validate_request()){
 return $this->json(['error_message'=>'Invalid token']);
 }
 // rest of the code
}

Flushing Token

Flushing a token means invalidating, clearing, or deleting all or particular CSRF token so they can no longer be used. There are two distinct ways to do this, depending on whether you want to flush the entire tokens or a specific token.

//flushing the entire CSRF tokens
$security->flush_token()
//flushing only token being validated
if(!$security->validate_request(flush: true)){
 // rest of your code
}

Warning!

Flushing CSRF tokens improves security by preventing replay attacks, but it can disrupt user experience when applied too aggressively. In single-use flushing (validate_token(flush: true)), deleting a token immediately upon submission breaks standard browser behaviors. If a user submits a form, navigates backward, and attempts to submit again, or if they work across multiple open browser tabs simultaneously, subsequent requests will fail with expired session errors because the original token was already consumed and removed from memory.

Global token flushing (flush_token()) carries even broader consequences by wiping out every active CSRF token stored in the user's session at once. This instantly invalidates all other open tabs, active background AJAX requests, and auto-save scripts, causing unexpected authorization failures across the entire application.

To balance security and usability, token flushing is best reserved for critical actions like logging out or changing credentials, while standard form submissions rely on time-based token expiration and automatic garbage collection instead.