public function onKernelResponse(FilterResponseEvent $event)
    {
        if (!$event->isMasterRequest()) {
            return;
        }

        if (!$event->getRequest()->hasSession()) {
            return;
        }

        if (null !== $this->logger) {
            $this->logger->debug('Write SecurityContext in the session');
        }

        $request = $event->getRequest();
        $session = $request->getSession();

        if (null === $session) {
            return;
        }

        if ((null === $token = $this->context->getToken()) || ($token instanceof AnonymousToken)) {
            if ($request->hasPreviousSession()) {
                $session->remove('_security_'.$this->contextKey);
            }
        } else {
            $session->set('_security_'.$this->contextKey, serialize($token));
        }
    }