Step-by-Step

After registering your app (see Developer and Application Registration) with the API provider and obtaining an OAuth client ID and client secret, it’s time to start writing code! Let’s go through each step of the flow and show how the protocol works. We’ll use PHP as the example programming language and the Google Tasks API along with Google’s OAuth 2.0 authorization server.

Although we’ll write the PHP code using the raw OAuth protocol, many API providers distribute client libraries for accessing their services. These libraries abstract away some of the details of implementing OAuth 2.0 and make it easier for developers. You can find information on Google’s PHP library, which works with Google Tasks, Google+, and many other Google APIs, at code.google.com.

Step 1: Let the user know what you’re doing and request authorization

Since the OAuth flow involves directing your users to the website of the API provider to obtain authorization, it’s a best practice to let them know in advance what will happen. You can do this by displaying a message, along with a link (the “Add tasks to your Google Tasks” link in Figure 2-2).

After the user initiates the flow, your application will need to send the user’s browser to the OAuth authorization page (as seen in Figure 2-3). This can be done either by sending the main browser window directly to the authorization endpoint or by creating a pop up. On this page, the API provider will present the user with a request to approve the application’s ...

Get Getting Started with OAuth 2.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.