MarkS
MarkS

Reputation: 127

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.

Upvotes: 0

Views: 2552

Answers (2)

Patrick
Patrick

Reputation: 368

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();

Upvotes: 6

seltzlab
seltzlab

Reputation: 340

My understanding is that you're using password grant type. This would require that your application knows a user and password pair to get a token. I would suggest instead to use client_credentials grant type.

Using the FOSOAuthServerBundle you should be able to get an access token with something like (in a ContainerAware context)

$this->get('fos_oauth_server.server')->grantAccessToken($request)

Here as you can see a Request object is required, but you can forge this object easily

In alternative you could try

$this->get('fos_oauth_server.server')->createAccessToken($client, null)

Where $client is an instance of you OAuth client.

Upvotes: 1

Related Questions