Cross-Site Request Forgery (CSRF) is a common web attack in which an attacker exploits a user's authenticated session to force the user to make a malicious request. To protect applications from CSRF attacks, Slim Framework provides a middleware mechanism. This article explains how to implement CSRF protection in Slim, including installation, middleware creation, application configuration, and token verification.
First, install Slim Framework using Composer. Execute the following command in the terminal to create a new Slim project:
composer create-project slim/slim my-app
Slim allows you to handle CSRF protection using middleware. To create CSRF protection, we need to define a middleware class named CsrfMiddleware.php. First, create a middlewares directory in the project root and then create the CsrfMiddleware.php file inside it.
Here's the code example for the CSRF middleware:
<?php namespace App\Middlewares; class CsrfMiddleware extends SlimMiddlewareAntiCsrf { public function call() { $this->app->hook('slim.before', [$this, 'check']); $this->next->call(); } public function validateStorage() { if (!$this->app->view()->getData('csrf_key') || !$this->app->view()->getData('csrf_value')) { $this->app->getLog()->error('CSRF validation error: missing CSRF key and/or value'); $this->app->pass(); } } }
Next, register the CsrfMiddleware in the Slim application. Add the following code to the index.php file to include the middleware:
$app = new SlimApp(); ... $app->add(new App\Middlewares\CsrfMiddleware()); ... $app->run();
To protect forms from CSRF attacks, we need to add CSRF tokens to the forms. This can be achieved by inserting hidden fields into the form. Here's an example of how to add a CSRF token:
<form action="/submit" method="post"> <input type="hidden" name="csrf_key" value="{{ csrf_key }}"> <input type="hidden" name="csrf_value" value="{{ csrf_value }}"> <!-- Other form fields --> <button type="submit">Submit</button> </form>
On the server side, we need to verify if the CSRF tokens in the submitted request are valid. Here's an example of a route handler that performs this verification:
$app->post('/submit', function ($request, $response) { $data = $request->getParsedBody(); // Retrieve request parameters // Check CSRF token $csrf_key = $data['csrf_key']; $csrf_value = $data['csrf_value']; if (!$app->csrf->check($csrf_key, $csrf_value)) { // CSRF token validation failed $response->getBody()->write('CSRF validation failed'); return $response->withStatus(403); } // Handle form submission // ... $response->getBody()->write('Form submitted successfully'); return $response; });
By using middleware in the Slim framework, we can easily implement CSRF protection. First, create the CSRF middleware to validate and handle the tokens, then add the CSRF tokens in the forms to secure user requests. This approach helps prevent CSRF attacks and enhances the overall security of your application.