Most Google APIs use the OAuth 2.0 protocol for authentication and authorization. In this post I am going to explain how to authenticate a web application to be able to use Google services. To read more about this authentication and authorization mechanism please click here.

Register Application

The very first thing you need to do is to register an application in Google API Console.

Google API Console

Click on the "Create an OAuth 2.0 client ID" to start creating your first client. If this is the first time you are creating a project, you have to fill in the information about your application. This information will be displayed on the prompt page, where user is asked to give permission to your application. Enter your company url in the Home Page URL field for now. You can also change this information later.

Create Client Id

Click next to fill in the information about your client application. You have to select the application type that is going to access the APIs. Since we are going to develop a web application I selected the Web Application from the items. The next two fields need careful attention. The first one is "Authorized Redirect URIs". You have to declare which pages of your web applications are going to have access to these APIs. That is, which page(s) in your web application is going to ask the user about the permissions. and it needs to be the complete URI to that page. Not that I have entered two URIs for my "Default" page. This is because IIS (and many other web servers) has url rewrite capabilities and in this case a user is able to access the default page by both URIs entered bellow (for more information look at url-rewrite). When adding authorized redirect URIs, I highly recommend that you add the links with ".cshtml" extension and without it. If you use URL Routing in your application, you might run into problems if you do not account for both redirections. "Authorized JavaScript Origins" also specifies where the JavaScript calls (to access the APIs) are originated from. This has to be your top level domain.

Create Client Id

Click "Create client ID" to create your first client ID. Once done, you are able to modify some of these settings later. For example adding more URIs to the "Authorized Redirect URIs" field.

Google API Console With App

Now that the client ID is ready (and consequently the client secret), we are able to develop the authentication procedure within our web application.

Obtain an Access Token from Google

The following code shows how to obtain an access token using the credentials created in the previous step. The explanation of the key concepts follows. Here is the C# code that sets the initial variables:

var TokenInformation = ""; 
var access_token = ""; 
//get the redirect URI 
var redirectURL = HttpContext.Current.Request.Url.AbsoluteUri.Split('?')[0]; 
//define Google web application credentials 
var clientid = "Your Client ID"; 
var client_secret = "Your Secret Key"; 
//define the application scope. 
var OAuthScope = "https://www.google.com/m8/feeds"; 

And the HTML code:

<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8" /> 
    <title>Google OAuth 2.0 Example</title> 
    <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" /> 
</head> 
<body> 
    <h1>Google OAuth 2.0 Example</h1> 
    <section> 
    <p>Click on the link below to authenticate your application:</p> 
    <a href="https://accounts.google.com/o/oauth2/auth?redirect_uri=@redirectURL.Trim()&response_type=code&client_id=@clientid&scope=@OAuthScope">Authenticate Me!</a> 
    <hr> 
    <p>@TokenInformation</p> 
    <p>Your Token is: <b>@access_token</b></p> 
    <hr> 
    </section> 
</body> 
</html>

Lets first look at the link provided in the html code. we create a GET request to “https://accounts.google.com/o/oauth2/auth” posting our Client ID, Client Secret, the redirect URL (which is identical to one of the URLs that we entered when we created our Client ID on Google API Console.), and the Scope. The scope defines the services on Google that our application wants to have access to. For example https://www.google.com/m8/feeds/ is the scope for accessing the Contacts API. To find the appropriate scope for your need refer click here. Once the user clicks on the “Authenticate Me!” link, he will be redirected to the Google authentication service to give permission to your application. But first things first, lets look at a possible error that might occur if you do not set the Redirect URL properly both in the Google Console API and in your web application. Remember: they have to be identical! Otherwise you will see this error:

GoogleErrorRedirect

If everything is set property, you should be able to see this message:

AuthenticationScreen

At this screen the user is prompted to give permission to your application. Once done, Google will post an authentication code to the page that requested the permission, and that page is nothing but the page that you have specified as the Redirect URL. Now looking at the C# code, we make sure that we have a code returned to our page. We can now use this code to request an access token from Google. Note that the access token can only be used to access the Contacts API in this example (Copy this code after the previous C# code).

//retrieve 'code value' from query string. 
var codeValue = Request["code"]; 
//If Google has sent us a 'code value' after authenticating the user, 
//we will use this code to request an access token. 
if (codeValue != null) { 
//Create a post request for to request an access token 
WebClient client = new WebClient(); 
// creates the post data for the POST request 
System.Collections.Specialized.NameValueCollection values = new System.Collections.Specialized.NameValueCollection(); 
values.Add("client_id", clientid); 
values.Add("client_secret", client_secret); 
values.Add("redirect_uri", redirectURL); 
values.Add("code", codeValue); 
values.Add("grant_type", "authorization_code"); 
// Post Request byte[] response = client.UploadValues("https://accounts.google.com/o/oauth2/token", values); 
TokenInformation = System.Text.Encoding.UTF8.GetString(response); 
access_token = Json.Decode(TokenInformation).access_token; 

I have used the WebClient library to create a post request to obtain the access token. Notice that we have to send the code value that we have obtained from the previous step to Google along with the other parameters. Also note that the request should be made to https://accounts.google.com/o/oauth2/token. I have decoded the response using the Json library to be able to easily grab the access token from the returned string. I highly recommend you do that as well! That was all you needed to do to get that precious access token! Now you are able to easily access the contact information of your clients. I will explain how it can be done in another blog post soon.