Accessing a Google API using OAuth2 in JavaScript

The instructions below describe how to create a JavaScript web application that accesses one of Google’s APIs using OAuth2.

1. If you have not already done so, install and activate a web server. If using Windows, the XAMPP package is recommended. Make a note of the location of the root document folder for the web server, perhaps at “C:\xampp\htdocs”.

2. Open a web browser.

3. If you have not already done so, create a Google account and then log in to that account.

4. In the web browser, navigate to the URL “https://console.developers.google.com“.

5. Click the “Create a project” button. In the dialog that appears, enter the value “OAuth2Test” in the Project name box, then click the “Create” button. Wait for the new project to be created.

6. A new dialog box titled “Credentials” will appear. (If it doesn’t, click on the “Credentials” item in the left-hand menu pane.) Click the “Create credentials” button, then select the entry titled “API key” from the list that appears.

7. A new dialog titled “API key created” will appear. Record the value in the “Your API key” box for later use, then click the “Close” button.

8. Click the “Create credentials” button again, and this time select the entry titled “OAuth client ID” from the list that appears. A warning message will appear stating that, “To create an OAuth client ID, you must first set a product name on the consent screen”.

9. Click the “Configure consent screen” button. On the “OAuth consent screen” tab that appears, enter the value “OAuth2Test” in the “Product name shown to users” box, then click the “Save” button.

10. Back on the “Create client ID” screen, click the “Web application” radio button. Enter the value “Oauth2Test” in the Name box that appears, and the value “http://localhost” in both the “Authorized JavaScript origins” and “Authorized redirect URIs” boxes beneath.

11. Click the “Create” button. Record the client ID and client secret that are displayed in the dialog that appears.

12. Enable the Google People API for the newly created project by navigating to the URL “https://console.developers.google.com/apis/api/people.googleapis.com/overview” and clicking the “Enable” button.

13. In the web server’s document folder (as determined in a previous step), create a new text file named “OAuth2.html”, containing the text from the code listing below. Substitute the API key and client ID obtained in the previous step at the end of the program, where indicated. This code is adapted from a sample found at the URL “https://developers.google.com/api-client-library/javascript/samples/samples“, under the heading “Authorizing and Making Authorized Requests”.


<html>
	
<body>

<button id="authorize-button" onclick="buttonAuthorize_Clicked()">Authorize</button>
<button id="signout-button" onclick="buttonSignout_Clicked()">Sign Out</button>

<script src="https://apis.google.com/js/api.js"></script>

<script type="text/javascript">

// ui event handlers

function buttonAuthorize_Clicked(event) 
{
	googleAPIClient.signIn();
}

function buttonSignout_Clicked(event) 
{
	googleAPIClient.signOut();
}

function GoogleAPIClient(googleAPI, apiKey, clientID)
{
	this.googleAPI = googleAPI;
	this.apiKey = apiKey;
	this.clientID = clientID;

	this.initialize();
}
{
	// public methods

	GoogleAPIClient.prototype.getUserGivenName = function() 
	{
		this.googleAPI.client.people.people.get
		(
			{
				resourceName: "people/me"
			}
		).then
		(
 			this.getUserGivenName_Success,
			this.getUserGivenName_Error
		);
	}

	GoogleAPIClient.prototype.getUserGivenName_Success = function(response) 
	{
		var givenName = 
			response.result.names[0].givenName;

		console.log
		(
			"Hello, " + givenName + "!"
		);
	}

	GoogleAPIClient.prototype.getUserGivenName_Error = function(reason) 
	{
		console.log
		(
			"Error: " + reason.result.error.message
		);
	}

	GoogleAPIClient.prototype.signIn = function()
	{
		this.googleAPI.auth2.getAuthInstance().signIn();
	}

	GoogleAPIClient.prototype.signOut = function()
	{
		this.googleAPI.auth2.getAuthInstance().signOut();
	}

	// initialization

	GoogleAPIClient.prototype.initialize = function() 
	{
		// Load the API client and auth2 library

		this.googleAPI.load
		(
			"client:auth2", 
			this.initialize_2.bind(this)
		);
	}

	GoogleAPIClient.prototype.initialize_2 = function() 
	{
		var initializerObject = 			
		{
			apiKey: this.apiKey,
			discoveryDocs: 
			[
				"https://people.googleapis.com"
					+ "/$discovery/rest?version=v1"
			],
			clientId: this.clientID,
			scope: "profile"
		}

		this.googleAPI.client.init
		(
			initializerObject
		).then
		(
			this.initialize_3.bind(this)
		);
	}

	GoogleAPIClient.prototype.initialize_3 = function() 
	{
		var authInstance = this.googleAPI.auth2.getAuthInstance();

		// Listen for sign-in state changes.
		authInstance.isSignedIn.listen
		(
			this.updateSigninStatus.bind(this)
		);

		// Handle the initial sign-in state.
		this.updateSigninStatus
		(
			authInstance.isSignedIn.get()
		);
	}

	// helper methods

	GoogleAPIClient.prototype.updateSigninStatus = function(isSignedIn) 
	{
		if (isSignedIn == true) 
		{
			this.getUserGivenName();
		}
	}

} // end class GoogleAPIClient

// run 

var googleAPIClient = new GoogleAPIClient
(
	gapi,
	"INSERT_API_KEY_HERE",
	"CLIENT_ID_HERE.apps.googleusercontent.com"
);

</script>

</body>

</html>

14. In the web browser, open the debugging pane (perhaps by pressing the F12 key) and make sure the Console sub-pane is visible.

15. In the web browser, navigate to the URL “http://localhost/OAuth2.html“. A page with two buttons, named “Authorize” and “Sign Out” will appear.

16. In another tab of the web browser, sign out of your Google account.

17. Click the “Authorize” button. On the dialog that appears, enter the username and password of a valid Google account (such as the one you just singed out of). If a dialog appears prompting for permissions, click the “Allow” button.

18. Verify that a customized greeting message is displayed in the debugging console pane.

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s