Let’s say you built an API using Symfony and you need to access it from a mobile application using authenticated requests on behalf of your users.

Here’s how to make this work using Symfony 2.8 and Doctrine.

Install FOSOAuthServerBundle

We will use the FOSOAuthServerBundle to implement this feature. Install it using the following command:

Next, enable the bundle in the AppKernel.php file:

Create OAuth model classes

To create the OAuth model classes just add the following files to your project. Here we already have FOSUserBundle installed and set up to use the ApiBundle\Entity\User class.





Configure FOSOAuthServerBundle

Import the routing configuration in your app/config/routing.yml file:

Add FOSOAuthServerBundle settings in app/config/config.yml:

Back to the models

Generate a migration and migrate the database:

…or, if you’re not using migrations, just update the database schema:

Configure your application’s security

Edit your app/config/security.yml file to add FOSOAuthServerBundle specific configuration:

Create a client

Before you can generate tokens, you need to create a Client using the ClientManager. For this, create a new Symfony command:

Now run the above command to generate your first OAuth client:

This client will be able to generate tokens and refresh tokens using the user’s username and password. You can find it’s data in the database client table. The token endpoint is at /oauth/v2/token by default.

Document using NelmioApiDocBundle

If you use the NelmioApiDocBundle to document your API, you can add these OAuth methods too. Create a new YAML file in src/ApiBundle/Resources/apidoc/oauth.yml:

Add a new NelmioApiYmlProvider.php file in src/ApiBundle/Service folder:

Add a new service in src/ApiBundle/Resources/config/services.yml file:

You’ll find now two /oauth/v2/token methods with different parameters listed in the api/doc section of your project.

That’s all! You can now use the generated client to authenticate your users in your mobile app using OAuth.

How to use the FOSOAuthServerBundle

First you will need to get an access token by making a POST request to the /oauth/v2/token endpoint with the following parameters:

You should get back something like this:

Use the access token for authenticated requests by placing it in the request header:

When the access token expires, you can get a new one using the refresh_token grant type at the same /oauth/v2/token endpoint:

The response should be similar to:

Need help with your next project?

Contact us

Privacy Preference Center