When I inject the security.context in my symfony2 service (twig extension) the following error appears:
Call to a member function getUser() on a non-object .....
class GeninnoShareboardExtension extends \Twig_Extension {
    public function __construct(ContainerInterface $container, SecurityContext $context) {
        $this->doctrine = $container->get('doctrine');
        $this->context = $context;
    }
    public function getUser() {
        return $this->context->getToken()->getUser();
    }
    ........
}
My services.yml looks like this:
services:
  geninno.twig.extension.dashboard:
    class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension
    arguments:
      container: "@service_container"
      service: "@security.context"
    tags:
     - { name: twig.extension }
A user is logged in and my firewall setup is like this:
access_control:
    - { path: ^/secured/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/secured/create, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/secured/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: [IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED] }
                You should try
services:
  geninno.twig.extension.dashboard:
    class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension
    arguments: [@service_container, @security.context]
    tags:
     - { name: twig.extension }
                        Is the page you are getting the error on behind a firewall? If not then it won't have access to the security token. You will need to put the page behind a firewall and then open it up to unauthenticated users.
something like this should do the trick to open the page up to unauthenticated users, but still have it inside a firewall (security.yml)
access_control:
  - { path: /lost_password, roles: IS_AUTHENTICATED_ANONYMOUSLY}
                        I solved it by adding an if to my SecurityContext calls. Checking if the GetToken() returned an object (authenticated) or string (anonymous)
if (is_object($this->context->getToken()))
{
    .... // getUser() etc.
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With