Open midnightLuke opened 5 months 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.
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.
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.
If a developer is using forms there should be an automated way to ensure CSRF protection on those forms.