简体   繁体   中英

Tell whether route is behind firewall in Symfony2

I'm currently writing an event listener in Symfony2, which listens for the kernel.response event, and adds a cookie to it if: a) a user is logged in, and b) no such cookie currently exists. It takes the service container as an argument.

However, I'm getting an error when the listener responds to events not behind a firewall (such as those in the dev toolbar) since the token is empty and an AuthenticationCredentialsNotFoundException is thrown. However, I can't for the life of me figure out how to tell whether the route is behind a firewall or not. Could anyone help?

Code

public function onKernelResponse(FilterResponseEvent $event) {
    // does the request have a device cookie?
    if ($this->container->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')
        && !$this->getRequest()->cookies->has(DeviceManager::COOKIE_PREFIX.'id')) {
        // no. Create one.
        $DeviceManager          =   $this->container->get('salus_user.device_manager');
        $Cookie                 =   $DeviceManager->createDeviceCookie();
        $Response               =   $event->getResponse();
        $Response->headers->setCookie($Cookie); // and save it
    }
    // else, yes, we don't need to do anything
}

Error

AuthenticationCredentialsNotFoundException in classes.php line 2888:

The token storage contains no authentication token. One possible reason may be that there is no firewall configured for this URL.

First check if token exist:

public function onKernelResponse(FilterResponseEvent $event) {
    if (!$this->container->get('security.token_storage')->getToken()) {
        return;
    }
    // Rest of code.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM