OAuth 2.0 PHP Client and Server Example

Setting up an OAuth2 provider is rather easy once you know how the protocol works. It's a 2-or-3 step process (depending on your set-up and whether you're getting tokens on behalf of a user or just from the server).

What you'll need:

  • Working code for an OAuth2 provider
  • Patience

What you'll need to figure out how to do on your code:

  • Create a client (public and private access tokens)
  • Figure out how the authorize and token endpoints are named (typically /authorize and /token)
  • Figure out how the scopes are dealt with

The first step to getting a token is to call /authorize?response_type=code&client_id=[YOUR ID]&redirect_uri=[YOUR REDIRECT URI]&scope=[YOUR SCOPE] , where:

  • clientid ([YOUR ID]) is your public access token
  • redirect_uri ([YOUR REDIRECT URI]) is your redirect URI. You will be redirected to this once you complete the autorize step
  • scope is the scope of your future token

On completion (there's usually a submit button), your browser will be redirected to the URI specified with a code in the URL (code=blah). Save this value.

When you've got this code, call the other endpoint: /token?client_id=[YOUR ID]&client_secret=[YOUR SECRET]&grant_type=authorization_code&scope=[YOUR SCOPE]&code=[YOUR CODE]&redirect_uri=[YOUR REDIRECT URI]

The parameters: - client_id - again, your client public key - client_secret - your private key (this is supposed to be a server-side call) - scope - the scope for the token - MUST MATCH THE FIRST CALL - redirect_uri - the redirect URI - MUST MATCH THE FIRST CALL - code - the code you received

If everything went okay, you'll see a JSON object on your screen containing the token info.

What happens in the background

Step 1 (authorize)

When you confirm the form, the server creates a temporary token (auth token as they're called), which typically has a very short life (my oauth2 sp code typically sets this to 60 seconds). This is the time your server has to go from receiving the code to triggering step 2. It is just a confirmation system, and its purpose is to also store the info provided in step 1 to prevent hijacks.

Step 2 (token)

This is where your access token is actually created. Lots of verifications, lots of stuff, but in the end, the token is just a value that links your client_id and your token. That's all it is.

Shameless plug: if you're using the Laravel framework, I've built exactly this from scratch (rather than using the crappy, undocumented sample code): http://bundles.laravel.com/bundle/oauth2-sp


PHP has a PECL client: http://www.php.net/manual/en/book.oauth.php

Nice intro on oauth2: http://www.slideshare.net/aaronpk/an-introduction-to-oauth-2

This site oauth2.net/2/ list out 3 oauth server in different stages of development.

Big providers (Facebook, Google, Yahoo, Twitter, etc) implements their own flavour of Oauth, and moreover Oauth 2.0 is still in draft revision, each provider follows a different revision