0

I have a very strange problem in one of my Symfony2's service. I want to get the current user in the constructor of my service but the SecurityContext->getToken return false!

That is my service constructor :

public function __construct(Registry $doctrine, SecurityContext $context){
    $this->doctrine = $doctrine;
    $this->context = $context;
    if(!$this->context->getToken()){
        echo "Il y a une merde au niveau du token !";
    }
    $this->my_auth = $this->getMyAuth();
}

And here the service declaration in my service.yml

security.autorisation:
    class: Nsi\SecurityBundle\Service\Autorisation
    arguments: [@doctrine,@security.context]

But when I go on my admin page, the message "Il y a une merde au niveau du Token" appear. the most surprising is that my bottom symfony toolbar show me my login !

My project is a Symfony 2.3.11 project

Thinks for your help

Fabien
  • 548
  • 7
  • 18
  • try isGranted() on context ! – guy_fawkes Mar 01 '14 at 16:55
  • 1
    cache the securityContext first and the call the getToken()->getUser() when needed (http://stackoverflow.com/questions/18770467/symfony2-why-gettoken-return-null-when-injecting-securitycontext-in-a-twigexte) – stwe Mar 01 '14 at 17:39
  • I need to execute a query in my constructor who use user informations. How can I use cache system for security context in my case ? – Fabien Mar 01 '14 at 17:46
  • Why do you need to run any query token related inside a service constructor? could you clarify your question please? – coma Mar 01 '14 at 18:02
  • I have tried your solution and it's work, but not fully optimized. I use this service many time in a page, so for optimise database connexions I think the best solution is to get my informations in constructor and put them in a property to get this in my function who is called many times. – Fabien Mar 01 '14 at 18:18
  • The security.context acts as a cache. Calling getToken multiple times wont hit the database. Are you injecting your Autorization class into an event listener? It seems like it is being used before the security listener has a chance to set it. – Cerad Mar 02 '14 at 08:01

2 Answers2

1

Don't call it from service constructor, because service initialization called earlier than authentication. That's why you have no token set.

Jekis
  • 4,274
  • 2
  • 36
  • 42
0

Try:

public function __construct(Registry $doctrine, SecurityContext $context){
    $this->doctrine = $doctrine;
    $this->context = $context;
    if(!$this->context->isGranted('ROLE_USER'))){
       echo "Il y a une merde au niveau du token !";
    }
    $this->my_auth = $this->getMyAuth();
}
Darmen Amanbay
  • 4,869
  • 3
  • 29
  • 50
  • not working. I have this error : AuthenticationCredentialsNotFoundException: The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL. – Fabien Mar 01 '14 at 17:40