Search code examples
symfonyfosoauthserverbundle

Symfony FOSOAuthServerBundle get tokens programmatically?


Using the standard endpoint for FOSOAuthServerBundle (with FOSUserBundle), I can retrieve an access and refresh token by providing a client_id, client_secret, user and password combination. The response looks like this:

{
  "accessToken": "YTg2ZTJkNTY2MGM5MGQyNzZjYjkyZWMwYzg1YTZmZTZmOTIyMzAxNDY2MTkwZDU5ODYzZTAzYmIyNDI0YTQ4ZQ",
  "expiresIn": 3600,
  "tokenType": "bearer",
  "refreshToken": "OTU1MGZhNDQ2ODFkZDUzMmQ4Y2FhNTk5OWM0NWFlNDk0YTY0ZDZhOTRjZTUwM2JlYTE3MDkxYzU3ZWY1OGRkYQ"
}

My question is, how can I retrieve similar data programmatically by passing in the client and user credentials? I.e. How can I make the same call from another part of my application without going via HTTP (slow), but rather directly via the bundle code (fast)?

I'm sure there must be an easy way of doing this, but the best I can find so far is this https://github.com/FriendsOfSymfony/FOSOAuthServerBundle/issues/347 which doesn't really achieve the same thing as the HTTP call.


Solution

  • Here is how you can get the same response directly from the fos_oauth_server.server service using a request object:

    $grantRequest = new Request(array(
            'client_id'  => $clientId,
            'client_secret' => $clientSecret,
            'grant_type' => 'password',
            'username' => $username,
            'password' => $password
        ));
    
    $tokenResponse = $this->get('fos_oauth_server.server')->grantAccessToken($grantRequest);
    
    $token = $tokenResponse->getContent();