2

Is there an easy way to get the current client on a controller using FOSOAuthServerBundle on Symfony?

I have some properties on my client entity and want to read them in a controller but i can't find the way to get the current client.

I've only found the way to get the current user ($this->container->get('security.context')->getToken()->getUser();), but not the current client.

EDIT: i've now found the way to get the client, but it's not showing me the values of the properties i added to my client entity. The following code:

$token = $this->container->get('security.context')->getToken()->getToken();
$accessToken = $this->container->get('fos_oauth_server.access_token_manager.default')->findTokenBy(array('token' => $token));
$client = $accessToken->getClient();
\Doctrine\Common\Util\Debug::dump($client);

is dumping:

object(stdClass)[1180]
public '__CLASS__' => string 'CC\APIBundle\Entity\Client' (length=26)
public '__IS_PROXY__' => boolean true
public '__PROXY_INITIALIZED__' => boolean false
public 'id' => int 6
public 'name' => null
public 'city' => null
public 'randomId' => null
public 'secret' => null
public 'redirectUris' => 
  array (size=0)
    empty
public 'allowedGrantTypes' => null

So the name and city that my client has on db is not showing... also i think there are many calls to db that could be avoided in a much elegant way...

Any ideas?

Noquepoaqui
  • 395
  • 3
  • 11
  • 1
    FYI: In the controller you can get current user simpler via `$this->getUser();` – NHG Feb 07 '14 at 13:01
  • Well, your controller needs to extend Symfony\Bundle\FrameworkBundle\Controller\Controller or you'll have to add that shortcut instead. – coma Feb 07 '14 at 13:31

2 Answers2

6
$tokenManager = $this->get('fos_oauth_server.access_token_manager.default');
$token        = $this->get('security.token_storage')->getToken();
$accessToken  = $tokenManager->findTokenByToken($token->getToken());

$client = $accessToken->getClient();
m4s0
  • 601
  • 6
  • 9
3
$tokenManager = $container->get('fos_oauth_server.access_token_manager.default');
$accessToken = $tokenManager->findTokenByToken(
    $container->get('security.context')->getToken()->getToken()
);
$client = $accessToken->getClient();

There is your client and you can't see the properties there because that's just a proxy. As soon as you request a property like:

$client->getName();

you'll see that the properties will be initialized.

Beware that $container is your service container, if you are inside a controller use $this->container to get your current one.

ggioffreda
  • 650
  • 6
  • 11