DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Full-Stack Observability Essentials: Explore the fundamentals of system-wide observability and key components of the OpenTelemetry standard.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Power of PHP Frameworks: Boosting Web Development With PHP Frameworks
  • Maximizing Laravel's Potential: A Guide to Driver-Based Services
  • The 9 Most Popular PHP Frameworks for Developers
  • Top 10 PHP Frameworks for Web Development

Trending

  • Log Analysis Using grep
  • TDD With FastAPI Is Easy
  • Demystifying Enterprise Integration Patterns: Bridging the Gap Between Systems
  • Automated Testing Lifecycle
  1. DZone
  2. Coding
  3. Frameworks
  4. CSRF Protection in Slim 3 PHP Framework

CSRF Protection in Slim 3 PHP Framework

Learn how to implement the Slim-Csrf Cross-Site Request Forgery protection library using the simplest use case.

Rob Allen user avatar by
Rob Allen
·
Aug. 26, 15 · Tutorial
Like (3)
Save
Tweet
Share
7.77K Views

Join the DZone community and get the full member experience.

Join For Free


in addition to the core slim framework , we also ship a number of add-ons that are useful for specific types of problems. one of these is slim-csrf which provides csrf protection.


this is middleware that sets a token in the session for every request that you can then set as an hidden input field on a form. when the form is submitted, the middleware checks that the value in the form field matches the value stored in the session. if they match, then the all is okay, but if they don't then an error is raised.


for the simplest use case, you need start the session and add the middleware:


session_start();
$app->add(new slim\csrf\guard());


then, from within a given route callable, you can create your form and add two hidden fields: one for the token's name and one for its value:


$app->get('/', function ($request, $response, $args) {
    // csrf token name and value
    $name = $request->getattribute('csrf_name');
    $value = $request->getattribute('csrf_value');

    // render a form
    $html = <<<eot
<!doctype html>
<html>
<head><title>csrf test</title></head>
<body>
    <form method="post" action="/process">
        <input type="hidden" name="csrf_name" value="$name">
        <input type="hidden" name="csrf_value" value="$value">
        <input type="text" name="name" placeholder="name">
        <input type="submit" value="go">
    </form>
</body>
</html>
eot;

    return $response->write($html);
});


if you run this in a browser and view the source, you'll see something like this:


slim csrf view source


refresh and you see different values for the csrf_name and csrf_value fields, which means that the user can have multiple tabs open and submit without any issues.


for testing, i created a simple route callable:


$app->post('/process', function ($request, $response, $args) {
    return $response->write("passed csrf check.");
});


pressing form's submit button will result in the display of "passed csrf check.". if you then refresh and confirm the post, you'll see "failed csrf check!" and the http status code will be 400.


customising the csrf failure


it's likely that you'll want to customise the csrf failure display as a plaint text error message isn't very user friendly! to change this, supply a callable to the guard class which has the same signature as middleware: `
function($request, $response, $next). the middleware must return a response.


this allows you to supply a custom error page:


$guard = new slim\csrf\guard();
$guard->setfailurecallable(function ($request, $response, $next) {
    return $response->write(<<<eot
<!doctype html>
<html>
<head><title>csrf test</title></head>
<body>
    <h1>error</h1>
    <p>an error occurred with your form submission.
       please start again.</p>
</body>
</html>
eot);
});
$app->add($guard);


as the failure callable has the middleware signature, you can also set a flag into $request and then deal with the csrf failure later. the failure callable would look something like this:


$guard->setfailurecallable(function ($request, $response, $next) {
    $request = $request->withattribute("csrf_result", 'failed');
    return $next($request, $response);
});


now, your route callable can decide what to do:


$app->post('/process', function ($request, $response, $args) {
    if (false === $request->getattribute('csrf_result')) {
        // deal with error here and update $response as appropriate
    } else {
        // successfully passed csrf check
        $response->write("passed csrf check.");
    }
    return $response;
});


this is very powerful and remarkably easy to set up.


summary


the flexibility of the failure callable allows you to handle a csrf validation failure in the most appropriate way for your application and is a very powerful feature of this middleware.


as it's psr-7 compliant, you can use the middleware independently of slim with any psr-7 middleware dispatch system that uses the middleware signature of function($request, $response, $next) where a response is returned.


PHP Framework

Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Power of PHP Frameworks: Boosting Web Development With PHP Frameworks
  • Maximizing Laravel's Potential: A Guide to Driver-Based Services
  • The 9 Most Popular PHP Frameworks for Developers
  • Top 10 PHP Frameworks for Web Development

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: