What is the best way to notify a user after an access_control rule redirects?

前端 未结 3 1078
庸人自扰
庸人自扰 2020-11-30 01:32

From Symfony 2.3 Security docs:

If access is denied, the system will try to authenticate the user if not already (e.g. redirect the user to th

3条回答
  •  天命终不由人
    2020-11-30 01:53

    I think a kernel.exception listener and setting a flash message can do it. Untested example:

    use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
    use Symfony\Component\HttpFoundation\Response;
    use Symfony\Component\HttpFoundation\Session\SessionInterface;
    use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
    
    class My403ExceptionListener
    {
        protected $session;
    
        public function __construct(SessionInterface $session)
        {
            $this->session = $session;
        }
    
        public function onKernelException(GetResponseForExceptionEvent $event)
        {
            $exception = $event->getException();
            if ($exception instanceof AccessDeniedHttpException) {
                $this->session->getFlashBag()->set('warning', 'You must login to access that page.');
            }
        }
    }
    

    Don't really know if it works or if it's the right thing. You can register it as kernel.event_listener. Or maybe it's better you wright a dedicated service and set it as the parameter of access_denied_handler in the firewall config. I think there a many possible ways.

提交回复
热议问题