I recently came across this little problem, and with the help of a couple posts I came up with the following solution.
To clarify the issue here, after logging out of a secured area we want to prevent any secured previous pages from being viewable again by clicking the back button. To do this, those previous pages must not be stored in the clients cache. We need to intercept every Symfony page response, check if its a secured page and if so, set the headers to return no-cache.
Step one, set up a response listener class:
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
class ResponseListener
{
public function onKernelResponse(FilterResponseEvent $event)
{
$request = $event->getRequest();
if ($this->disableThisPageCache($request->getPathInfo())) {
$headers = $event->getResponse()->headers;
$headers->set('Cache-Control', 'no-cache, no-store, must-revalidate'); // HTTP 1.1.
$headers->set('Pragma', 'no-cache'); // HTTP 1.0.
$headers->set('Expires', '0'); // Proxies.
}
}
private function disableThisPageCache($currentPath)
{
$paths = array('/admin', '/customer');
foreach ($paths as $path) {
if ($this->checkPathBegins($currentPath, $path)) {
return true;
}
}
return false;
}
private function checkPathBegins($path, $string)
{
return substr($path, 0, strlen($string)) === $string;
}
}
Step 2, register it as a service:
app.filter_response_listener:
class: AppBundle\EventListener\ResponseListener
tags:
- { name: kernel.event_listener, event: kernel.response }
Step 3, set the $paths
array to contain the secured path(s) for your application. If you need to find out these, look in your security.yml file under the access_control section.
There is probably a better way of checking if the page is in a secured area, using the Symfony Security service, but this solution works for my application.
Credit to these posts that helped me: