PHPackages                             lithemod/csrf - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. lithemod/csrf

ActiveLibrary

lithemod/csrf
=============

The CSRF (Cross-Site Request Forgery) middleware in Lithe protects your application from attacks that attempt to perform actions on behalf of the user without their authorization.

v1.0.1(1y ago)015MITPHP

Since Oct 2Pushed 1y agoCompare

[ Source](https://github.com/lithemod/csrf)[ Packagist](https://packagist.org/packages/lithemod/csrf)[ RSS](/packages/lithemod-csrf/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (5)Versions (3)Used By (0)

CSRF
====

[](#csrf)

The CSRF (Cross-Site Request Forgery) middleware in Lithe is a security layer that protects your application from attacks that attempt to perform actions on behalf of the user without their authorization. These attacks can occur when an authenticated user accesses a malicious site that tries to send requests to your application.

Installation
------------

[](#installation)

To install the CSRF middleware in your Lithe application, use Composer. Run the following command in your terminal:

```
composer require lithemod/csrf
```

Using the CSRF Middleware
-------------------------

[](#using-the-csrf-middleware)

The CSRF middleware should be configured in your Lithe application to protect routes that alter the state of the application (such as POST, PUT, DELETE). To configure it, add it to your application using the `use()` method on an instance of the Lithe application, and provide an array of configurations:

```
use Lithe\Middleware\Security\csrf;

$app->use(csrf([
    'expire' => 600, // Token expiration time in seconds
]));
```

### Middleware Configurations

[](#middleware-configurations)

The following configurations are available for the CSRF middleware:

- **name** (string): The name of the CSRF token. The default is `_token`. You can change it to meet your needs, for example, if you are using a frontend framework that expects a different token name.
- **expire** (int): The expiration time of the token in seconds. The default is 600 seconds (10 minutes). This value should be balanced between security and usability; very low values may frustrate users.
- **checkBody** (bool): Indicates whether the token should be verified in the request body. The default is `false`. If enabled, this ensures that the token is validated even in methods like PUT or DELETE.
- **bodyMethods** (array): HTTP methods for which token validation should be applied if the `checkBody` configuration is enabled. The default is `['POST']`. This is useful if you have endpoints that modify data using other HTTP methods.
- **regenerate** (bool): Indicates whether the token should be regenerated on each request. The default is `false`. Enabling this can enhance security, but it may impact user experience in some cases.

Example configuration in a route:

```
$app->use(csrf([
    'name' => '_csrf_token',
    'expire' => 900, // 15 minutes
    'checkBody' => true,
    'bodyMethods' => ['POST', 'PUT', 'DELETE'],
    'regenerate' => true,
]));
```

### Generating and Retrieving CSRF Tokens

[](#generating-and-retrieving-csrf-tokens)

The CSRF middleware generates a unique token for each session. You can generate and retrieve the token using the following methods within a route:

```
$app->get('/generate-token', function ($req, $res) {
    $token = $req->csrf->generateToken();
    return $res->json(['token' => $token]);
});

$app->get('/get-token', function ($req, $res) {
    $token = $req->csrf->getToken();
    return $res->json(['token' => $token]);
});
```

The `generateToken` method has an optional parameter that, when set to `true`, forces the generation of a new token.

### Including the CSRF Token in Forms

[](#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) {
    $tokenField = $req->csrf->getTokenField();
    return $res->send("

            $tokenField

            Submit

    ");
});
```

### Verifying CSRF Tokens

[](#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 verify the validity of the token:

```
$app->post('/submit', function ($req, $res) {
    $token = $req->input('_csrf_token'); // Change to the token name if necessary
    if ($req->csrf->verifyToken($token)) {
        // Process the request
        return $res->json(['message' => 'Data submitted successfully!']);
    } else {
        // Handle the invalid token
        return $res->status(419)->json(['error' => 'Invalid CSRF token!']);
    }
});
```

### Token Manipulation Functions

[](#token-manipulation-functions)

Here are some useful functions for CSRF token manipulation:

- **invalidate()**: Destroys the CSRF token and its associated session variable, invalidating it.

```
$app->post('/invalidate-token', function ($req, $res) {
    $req->csrf->invalidate();
    return $res->json(['message' => 'CSRF token invalidated!']);
});
```

- **exists()**: Checks if a CSRF token exists in the session.

```
$app->get('/check-token', function ($req, $res) {
    $exists = $req->csrf->exists();
    return $res->json(['token_exists' => $exists]);
});
```

Security Considerations
-----------------------

[](#security-considerations)

1. **Application Security**: Using the CSRF middleware is essential for application security. Always include the token in all forms that submit modifiable data and in AJAX requests. The absence or invalidity of the token should be handled appropriately, usually resulting in redirects or error messages.
2. **Token Expiration**: Configure the token expiration time to balance security and usability. Expired tokens should be regenerated, and the user should be notified if they attempt to use an invalid token.
3. **Body Verification**: Enabling body verification (`checkBody`) increases security, especially in APIs that use methods like PUT and DELETE. However, this may add overhead to request processing, so evaluate your application’s needs.
4. **Token Regeneration**: Enabling token regeneration on each request increases security, but it can also cause issues if users attempt to submit forms quickly. Use this with caution and test to ensure an adequate user experience.
5. **Error Handling**: Be prepared to handle HTTP 419 exceptions thrown when the CSRF token is invalid or missing. Appropriate handling may include redirecting to an error page, displaying a user-friendly message, or even logging attack attempts for later analysis.
6. **Monitoring and Analysis**: Consider implementing logging to monitor CSRF attack attempts. This can help identify suspicious patterns and further strengthen your application’s security.

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity6

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

2

Last Release

591d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/56173de3a7bf7099dd8168efd730d3c2fb5df5174a123fdc37cee8c3589e2345?d=identicon)[williamhumbwavali](/maintainers/williamhumbwavali)

---

Top Contributors

[![williamhumbwavali](https://avatars.githubusercontent.com/u/127023095?v=4)](https://github.com/williamhumbwavali "williamhumbwavali (2 commits)")

---

Tags

csrflithemiddlewarephp

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/lithemod-csrf/health.svg)

```
[![Health](https://phpackages.com/badges/lithemod-csrf/health.svg)](https://phpackages.com/packages/lithemod-csrf)
```

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
