CSRF
The CSRF (Cross-Site Request Forgery) middleware in Lithe protects your application against attacks that attempt to perform actions on behalf of the user without their authorization.
Installing the CSRF Middleware
To install the CSRF middleware, use Composer:
composer require lithemod/csrf
You can find more information and the source code for the module at github.com/lithemod/csrf.
Using the CSRF Middleware
The CSRF middleware in Lithe is designed to protect your application against Cross-Site Request Forgery (CSRF) attacks. To configure it, add it to your application using the use() method on an instance of the Lithe application:
use Lithe\Middleware\Security\csrf;
$app->use(csrf([
    'expire' => 600,
]));
Middleware Configuration
The CSRF middleware can be configured with the following parameters in an array:
- name (string): The name of the CSRF token. The default is _token.
- expire (int): The expiration time of the token in seconds. The default is 600 seconds.
- checkBody (bool): Indicates whether the token should be checked in the body of the request. The default is false.
- bodyMethods (array): HTTP methods for which the token validation should be applied if the checkBodysetting is enabled. The default is['POST'].
- regenerate (bool): Indicates whether the token should be regenerated on each request. The default is false.
Example configuration within a route:
$app->use(csrf([
    'name' => '_token',
    'expire' => 600,
    'checkBody' => true,
    'bodyMethods' => ['POST', 'PUT', 'DELETE'],
    'regenerate' => true,
]));
Generating and Obtaining CSRF Tokens
The CSRF middleware generates a unique token for each session. You can generate and obtain the token using the following methods:
- 
generateToken(bool $force = false): string 
 Generates a new CSRF token and stores it in the session. If$forceistrue, a new token will be generated even if one already exists.$app->get('/', function ($req, $res) { $token = $req->csrf->generateToken(); // Additional logic });
- 
getToken(): string 
 Returns the current CSRF token stored in the session.$app->get('/', function ($req, $res) { $token = $req->csrf->getToken(); // Additional logic });
Including the CSRF Token in Forms
To include the CSRF token in HTML forms, use the getTokenField() method to generate a hidden field with the token:
$app->get('/form', function ($req, $res) {
    $res->send($req->csrf->getTokenField());
});
Verifying CSRF Tokens
The middleware automatically verifies the token in POST requests and other methods specified in bodyMethods when the checkBody option is enabled. If the token is invalid or missing, an HTTP 419 exception will be thrown. If checkBody is disabled, you can use the following methods to check the validity of the token:
- 
verifyToken(string $token, bool $checkBody = false): bool 
 Verifies whether the provided CSRF token is valid. If$checkBodyistrue, it checks the token in the body of the request; otherwise, it checks in the session.$app->post('/submit', function ($req, $res) { $isValid = $req->csrf->verifyToken($req->input('_token')); // Additional logic });
Token Handling Functions
- 
invalidate(): void 
 Destroys the CSRF token and its associated session variable, invalidating it.$app->get('/invalidate', function ($req, $res) { $req->csrf->invalidate(); });
- 
exists(): bool 
 Checks if a CSRF token exists in the session.$app->get('/', function ($req, $res) { $exists = $req->csrf->exists(); // Additional logic });
Considerations
- Security: Ensure that the CSRF token is included in all forms that submit modifiable data and in AJAX requests to prevent CSRF attacks. Proper validation and inclusion of the token are essential for adequate protection.
- Token Expiration: Configure the expiration time of the token carefully to balance security and usability. Expired tokens are regenerated to avoid authentication issues.
- Body Checking: If checkBodyis enabled, the token will be checked in both headers and the body of the request. This is useful for APIs receiving tokens via POST, PUT, or DELETE but may add extra overhead.
- Token Regeneration: When regenerateis enabled, a new token is generated on each request. This can enhance security but should be used cautiously to avoid impacting user experience.
- Error Handling: Be prepared to handle HTTP 419 exceptions thrown when the CSRF token is invalid or missing. This may include redirecting to an error page or displaying an appropriate message to the user. For more information on handling HTTP exceptions, see the HTTP Exceptions documentation.