Search code examples
symfonysecurity-context

SecurityContext->isGranted() working in controller but not in service


I have a public area of my app accesible with no login or authentication, and when I run this code in a controller if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY')) I get a true as expected.

Then I have a service defined like this:

main.services:
    class: App\MainBundle\Services\MainServices
    arguments: [ @doctrine.orm.entity_manager, @security.context, @service_container ]

But when I run this code:

public function __construct(EntityManager $em, SecurityContext $securityContext, Container $container) {
    $this->em = $em;
    $this->container = $container;
    $this->securityContext = $securityContext;

    error_log("MAIN");
    if ($securityContext->isGranted('IS_AUTHENTICATED_ANONYMOUSLY'))
        error_log("MAIN Anon");
    else
        error_log("MAIN no anon");
}

I get an exception:

Uncaught exception 'Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException' with message 'The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.'

The service is invoked right after the first command in controller.

Thank you


Solution

  • This error could occur when service initializes before security token created. Try not to check access in constructor, move this check to method, called from your controller.