Display flash messages after login/logout
You can access the SecurityContext
from your Controller
. So, assuming your forbidden area require a role SOME_ROLE
, you can do something like:
if (!$this->get('security.context')->isGranted('SOME_ROLE')) {
$this->get('session')->getFlashBag()->add('error', 'Access forbidden');
// maybe return a RedirectResponse to another page the user can access...
}
Note that the SecurityContext
has been deprecated since Symfony 2.6. It will still work, but if you want to learn how to adapt to future versions, you can check this.
As for the messages when users are/aren't logged in, you can use the AuthorizationChecker
, very similar to the previous one:
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
// Add flash message here...
}
You can find more information here.
It will take some time and some coding just to display a simple message. If you want to do it by Symfony way you should look at this security configuration first, especially these ones:
entry_point
(under firewall) - which usually redirects users to login page whenever they try to access the secured pages. You can set flash messages here.success_handler
underform_login
(if you're using it) to show your successful login messagesuccess_handler
underlogout
to show your logout message
Some references:
- SecurityBundle Configuration ("security")
- Symfony2: why access_denied_handler doesn't work
- What is the best way to notify a user after an access_control rule redirects?
- Redirect Symfony2 LogoutSuccessHandler to original logout target
- Adding a Flash Message