Symfony2 user access from twig extension service

When I insert security.context into my symfony2 service (twig extension), the following error appears:

Calling the member function getUser () for 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 is as follows:

 services: geninno.twig.extension.dashboard: class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension arguments: container: "@service_container" service: "@security.context" tags: - { name: twig.extension } 

The user is logged in and my firewall setup looks 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] } 
+6
source share
3 answers

I solved this by adding if to my SecurityContext calls. Checking whether GetToken () returned an object (authenticated) or a string (anonymous)

 if (is_object($this->context->getToken())) { .... // getUser() etc. } 
+1
source

You must try

 services: geninno.twig.extension.dashboard: class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension arguments: [@service_container, @security.context] tags: - { name: twig.extension } 
+2
source

Is the page you receive the error message behind the firewall? If not, he will not have access to the security token. You will need to place the page behind the firewall, and then open it for unverified users.

something like this should do the trick to open the page before unauthenticated users, but still have it inside the firewall (security.yml)

 access_control: - { path: /lost_password, roles: IS_AUTHENTICATED_ANONYMOUSLY} 
+1
source

All Articles