Symfony 2 Access Denied Listener - Insane Visions

Symfony 2 Access Denied Listener

If you have say, an admin and a user role – if a user tries to access the engine, we just want to redirect them back to the previous page (if we can) or if not, to the homepage. Let’s start out with the config.

Above is an example config.yml file for your symfony application. We set the parameter class (to keep things neat and quick to update with numerous services) that we then used in our kernel listener called ‘accessDenied’. Here we pass in the class that this resides in, we include scope request that way we can try and get the referer page. Arguments passed in of “@session” is used for the flash message, “@router” is used to redirect the user back home if no referrer and “@request” for the same reason as scope request.

The tags we pass in are also typical of other kernel listeners – kernel.event_listener, the event being a kernel.exception and the method is of course the function name where we do this.

As mentioned in the config.yml file, we are passing in the session (flash message), router (redirect to named route) and request (redirect to previous page if possible). Where the real magic happens is in the ‘onAccessDeniedException’ function.

First, we check to see if the message is access denied (this is for all exceptions, after all) – if it is anything other than that, the exception runs as normal. The flash message is set with type and message – then if there is a referer, that is set as the redirect, if not, enter in the name of your homepage route. Lastly, the event response is set as the redirect to one of thos pages and the flash message will appear (assuming you have this setup) on the page you are sent to.

This is one of those small nitty gritty things, but quite useful. I highly recommend checking out services and listeners, very powerful.

Hoping to start a line of these mini-tutorials, I’m going to start today with a small script utility for Symfony 2 that will redirect users with a flash message accessing a page they aren’t alowed to. I should note, this will not interfere with Symfony’s authentication that will redirect a non-logged in user to the login page – that is something separate.