在 login/logout 之后显示即显消息
Display flash messages after login/logout
我一直在关注 this tutorial Symfony 手册来管理我的用户。
现在,我想在登录成功后或有人试图访问禁区时设置一个闪现消息。
我的理解是身份验证和授权不是在控制器内部管理的。因此,我不知道将我的代码放在哪里以显示简单的 "Sorry, you are not connected" 消息。
您可以从 Controller
访问 SecurityContext
。所以,假设你的禁区需要一个角色SOME_ROLE
,你可以这样做:
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...
}
请注意,SecurityContext
自 Symfony 2.6 以来已被弃用。它仍然可以工作,但是如果你想了解如何适应未来的版本,你可以查看this。
至于用户are/aren未登录时的消息,您可以使用AuthorizationChecker
,与上一个非常相似:
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
// Add flash message here...
}
您可以找到更多信息here。
仅显示一条简单的消息将需要一些时间和一些编码。如果你想通过 Symfony 的方式做到这一点,你应该首先查看 this 安全配置,尤其是这些:
entry_point
(在防火墙下)——每当用户尝试访问安全页面时,通常会将用户重定向到登录页面。您可以在此处设置即显消息。
success_handler
在 form_login
下(如果您正在使用它)显示您成功登录的消息
success_handler
在 logout
下显示您的注销消息
一些参考资料:
- 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
我一直在关注 this tutorial Symfony 手册来管理我的用户。
现在,我想在登录成功后或有人试图访问禁区时设置一个闪现消息。
我的理解是身份验证和授权不是在控制器内部管理的。因此,我不知道将我的代码放在哪里以显示简单的 "Sorry, you are not connected" 消息。
您可以从 Controller
访问 SecurityContext
。所以,假设你的禁区需要一个角色SOME_ROLE
,你可以这样做:
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...
}
请注意,SecurityContext
自 Symfony 2.6 以来已被弃用。它仍然可以工作,但是如果你想了解如何适应未来的版本,你可以查看this。
至于用户are/aren未登录时的消息,您可以使用AuthorizationChecker
,与上一个非常相似:
if (!$this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
// Add flash message here...
}
您可以找到更多信息here。
仅显示一条简单的消息将需要一些时间和一些编码。如果你想通过 Symfony 的方式做到这一点,你应该首先查看 this 安全配置,尤其是这些:
entry_point
(在防火墙下)——每当用户尝试访问安全页面时,通常会将用户重定向到登录页面。您可以在此处设置即显消息。success_handler
在form_login
下(如果您正在使用它)显示您成功登录的消息success_handler
在logout
下显示您的注销消息
一些参考资料:
- 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