Setting up OAuth doesn’t have to be a pain. There are tons of well-written and documented libraries for OAuth out there that are easy to use. If you want to authenticate against one of the larger sites on the web, like Facebook and Google, chances are that you don’t have to do much more than installing the library and setting up some routs for the auth callback. In this post, I’m going to walk through a slightly more complex scenario, where we are gonna authenticate against Basecamps API.
The first thing we need to do is to download the OAuth library that we want to use. In this post, I’m gonna use the league/oauth2-client which is a well-tested PHP library for OAuth2 authentication. We do this by using composer.
Next, we need to create a custom OAuth provider for Basecamp, since it is not one of the already implemented OAuth providers in the library. We create a class called BasecampOAuth that extends the Abstract provider from the league/oauth2-client library. All information needed to set this up comes from Basecamps API documentation.
Now we need to set up the routes to handle the OAuth requests and response.
Using Laravel the controller functions would look something like this:
… and the routes for the OAuth registration and callback would look something like this:
We initialize the BasecampOAuth class using the Laravel IoC container for dependency injection. Add this code with your other IoC initialization code, or in bootstrap/start.php.
Now we just need to get the access token from the current session with Session::get('accessToken') and append it to the API calls.
To get the client Id and secret and start building your own app you need to register here!
If you want to do OAuth authentification using services from Google, Facebook, or some of the other providers already included in the league/oauth2-client library, you can just skip the first step and use the library provider when implementing the controller code.