Simple OAuth2 authorization code grant example using PHP and cURL

The authorization code grant methods, should be very familiar if you’ve ever signed into an application using your Facebook or Google account.

The flow is quite simple. The application redirects the user to the authorization server >> the user will then be asked to log in to the authorization server and >> approve access to his data. And if the user approves the application  >> he will be redirected back to the application.

So let’s start preparing the authorization code grant example.

We are using PHP v5.6.32 and cURL enabled extension on a Windows localhost machine. If you are using XAMPP you normally just have to uncomment this line to have cURL enabled.

you can find it in xampp\apache\bin\php.ini  or  xampp\php\php.ini , depending on your XAMPP version and then restart Apache service.

So first you will need to collect your data and prepare some vars:

Now build your first URL to call. Normally you will want to call this URL in a popup window like old school times. You can also try a modern modal and use an iFrame but that didn’t work for me.

After the user enters his credentials and gives application access the Identity provider will redirect to the CALLBACK_URL with a “code”.

You will see the code in the URL, so this is the GET method.

So just use GET to retrieve the code param. Like this:  $code = $_GET['code'];

This code is only valid for a short period of time and you will have to exchange the code for a token so you can make API calls. Here is the curl POST for receiving the token key:

 

If everything goes fine, you should get a JSON response similar to this one:

You can now use this token to make API calls and retrieve the info you’re after. You normally do a request to your endpoint using the token like this:

Just a small note here: token is normally valid for a short-to-medium period of time. When the token expires you can use the refresh token to request a new token. The refresh token should always be kept a secret on the server side, but this is subject of a new tutorial.

Still here?? Let me know your experience and maybe I can help you out there.

Leave a Reply

Your email address will not be published. Required fields are marked *