PHP Luminova: Cross-Site Request Forgery (CSRF) Protection
Luminova’s CSRF protection for form submissions and browser requests authenticated by cookies, including token generation, storage, and validation.
Cross-site request forgery (CSRF) can occur when a browser automatically includes a user’s credentials, such as a session cookie, in a request initiated by another site. Luminova’s CSRF class provides tokens to protect requests that change application state.
The browser submits the token in a hidden form field or the X-CSRF-Token header. The application validates the token before processing the action and rejects requests with a missing or invalid token.
Usages
To change how the CSRF token is stored. Either in session or cookie, update the session configuration setting.
Storage Options:
session– Stores the token in PHP session data (default).cookie– Stores the token in a browser cookie when cookie storage is configured or PHP sessions are unavailable.
Example:
// In App\Config\Session
public string $csrfStorage = 'session';For more details, see the Session Configuration section.
Protecting Requests
In HTML Forms
Use inputToken() or getToken() to include a CSRF token as a hidden input in any form that performs POST, PUT, or DELETE actions.
<form method="POST" action="/submit">
<?php
// Option 1: Automatically generate a hidden CSRF input
Luminova\Security\CSRF::inputToken();
// Option 2: Manually include token
// <input type="hidden" name="csrf_token" value="<?= Luminova\Security\CSRF::getToken(); ?>">
?>
<input type="text" name="username" required>
<button type="submit">Submit</button>
</form>When the form is submitted, the token is sent with it and later verified on the server.
In AJAX Requests
Include the CSRF token in a meta tag, then attach it to every AJAX request header.
<head>
<?= Luminova\Security\CSRF::metaToken(); ?>
<!-- Example output: <meta name="csrf_token" content="eut9n..."> -->
</head>Attach the token when sending data with JavaScript:
const csrfToken = document.querySelector('meta[name="csrf_token"]').getAttribute('content');
fetch('/api/update', {
method: 'POST',
headers: { 'X-CSRF-Token': csrfToken },
body: JSON.stringify({ data: 'example' })
});Tip:For single-page applications or AJAX-heavy pages, refresh the token from the backend after each submission and update the meta tag value.
Verifying Token on Submission
Validate the CSRF token before processing any submitted data. Reject the request if the token is missing or invalid.
// app/Controllers/Http/MyController.php
use Luminova\Security\CSRF;
$csrfToken = $this->request->getCsrfToken();
// Or method specific
// $csrfToken = $this->request->getPost('csrf_token');
if ($csrfToken !== null && CSRF::validate($csrfToken)) {
// Token is valid; now refresh it to prevent reuse
CSRF::refresh();
echo 'Action completed, token refreshed.';
} else {
echo 'Invalid CSRF token. Request blocked.';
}Recommendation:Successful validation consumes the token by default. Generate a replacement when rendering the next form or returning a fresh token to the client.
Checking Token Availability
Check whether a token has already been generated before creating one manually.
use Luminova\Security\CSRF;
if (!CSRF::hasToken()) {
$token = CSRF::refresh(); // Generate a new one if missing
}Deleting a Token
Remove the stored token when a user logs out or when ending a session to prevent reuse.
use Luminova\Security\CSRF;
// During logout or session cleanup
CSRF::delete();Class Definition
- Full namespace:
Luminova\Security\CSRF - This class is final.
Constants
| Constant | Value | Meaning |
|---|---|---|
INPUT_NAME | csrf_token | Field name emitted by the token helpers. |
Methods
getToken
Retrieves a previously generated CSRF token or generates a new token if none was found, then stores it.
public static function getToken(): stringReturn:
string - Return the generated CSRF token.
refresh
Generates a new CSRF token and stores it.
public static function refresh(): stringUse this method when you need to regenerate a token after validation.
Return:
string - Return the generated CSRF token.
delete
Delete stored CSRF token.
public static function delete(): voidinputToken
Generates and displays an HTML hidden input field for the CSRF token.
public static function inputToken(): voidmetaToken
Generates and displays an HTML meta tag for the CSRF token.
public static function metaToken(): voidvalidate
Validates a submitted CSRF token.
public static function validate(string $token, bool $reusable = false): boolParameters:
| Parameter | Type | Description |
|---|---|---|
$token | string | The token submitted by the user. |
$reusable | bool | Keep the token after successful validation. Defaults to false, which consumes the token. |
Return:
bool - Return true if the submitted token is valid, false otherwise.
hasToken
Check if a token has already been generated.
public static function hasToken(): boolReturn:
bool - Returns true if a token has already been created, otherwise false.
getHeader
Return the current token in an array suitable for setting a request header.
public static function getHeader(): arrayReturn:
array{X-CSRF-Token:string} - The token header and its value.
| Key | Type | Description |
|---|---|---|
X-CSRF-Token | string | The current token. |