forestcitylabs / framework

A PSR compliant framework for building web applications.
https://forestcitylabs.github.io/framework/
GNU General Public License v3.0
0 stars 0 forks source link

CSRF Protection #47

Open midnightLuke opened 3 weeks ago

midnightLuke commented 3 weeks ago

If a developer is using forms there should be an automated way to ensure CSRF protection on those forms.

midnightLuke commented 3 weeks ago

I believe the best way to implement this would be as a middleware that passes the request on and simply checks if the CSRF token is passed in the response data, puts that in the session and then checks it against any future PUT, POST, PATCH or DELETE requests made during that session. If a new token is generated it should override the previous token and only allow one CSRF token per session, so the name of the token can be hard-coded.

midnightLuke commented 3 weeks ago

Usage would look something like this:

<?php

$token = Csrf\Token::generate();
return $this->response_factory->generateResponse()->withAttribute('_csrf', $token);

This would require the developer to insert the token into the form with as so:

<input type="hidden" name="_csrf" value="{{token}}" />

This might be prone to lazy/forgetful developers creating security holes though, we could create the middleware such that it requires a CSRF token for all such requests and failure to provide the token results in a 400 response outright. Then we would need to allow whitelisting in the middleware and/or a strict_mode parameter that enforces the CSRF behaviour.

midnightLuke commented 3 weeks ago

Looks like withAttribute is only for requests, not responses, so the developer would be required to put it into the session as well, which would not be ideal.