Home > Uncategorized > Hello World, OAUTH

Hello World, OAUTH

OAuth

OAUTH is an authentication system used by companies such as Google, Twitter, Vimeo, Linked in etc, and it is much more complex than basic authentication, but it really is just about exchanging data between your server and the authentication provider.

This is meant to be a “Hello World” example, showing an easy way to implement OAuth 2, without using any third party frameworks.

The example uses C# (ASPX), and Google API. I will be demonstrating a call to Google Analytics API, but any Google API works similarly. I can’t say the same for Twitter / Vimeo / LinkedIn, but the flow of data should be the same.

Prerequisites:

  • Some windows hosting to host the callback page
  • Sign up through the Google API Console to the Google Analytics API, and set up a client ID for Web Applications

Flow of actions overview:

The reason why OAuth is popular, is because it means that API consumers (i.e. you), don’t get to see user’s Google credentials.  You never ask the user for their username and password, you send them to Google and Google enter their username and password on Google’s page. Google will then send you back “proof” that the username and password were correct, but will never tell you what the username and password was.

The first step, therefore is to send a user to google using a special link. A simple link like this does:

<a href=”https://accounts.google.com/o/oauth2/auth?state=%2Fprofile&redirect_uri=http%3A%2F%2Fdananos.brinkster.net%2Foauth%2Fcallback.aspx&response_type=code&client_id=540622200787-bdm94elvkgshgl12inm99qug33jav38b.apps.googleusercontent.com&approval_prompt=force&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics”&gt;
Login</a>

Let’s break down that link:

https://accounts.google.com/o/oauth2/auth?state=%2Fprofile
&redirect_uri=http%3A%2F%2Fdananos.brinkster.net%2Foauth%2Fcallback.aspx
&response_type=code
&client_id=540622200787-bdm94elvkgshgl12inm99qug33jav38b.apps.googleusercontent.com
&approval_prompt=force
&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics

The important bits are:

client_id – You get this from your Google API Console

redirect_uri – You set this in your Google API, and it tells Google where to send the user after they have logged in.

scope – This sets which APIs you would like to use, In my case, Google Analytics.

Once the user signs into Google, then it’s up to some server-side code to interpret the response from Google, and use it to access Google’s APIs using the user’s credentials. This is where the callback script comes in, which is simply an ASPX page that is hosted on your server.

The steps that this script must do is:

  • 1. Exchange the authorisation code provided by Google into a access token
  • 2. Use the access token when calling Google’s API methods.

Let’s deal with the first step, the exchange of the authorisation code.

Google will redirect back to your URL with extra parameters, like this:

callback.aspx?state=/profile&code=4/l_QKG8_zbhRi-hi9yhRXEyoUqHc8.wrb2xyoo0IQfOl05ti8ZT3bDNXF_gQI

The code value needs to be sent to https://accounts.google.com/o/oauth2/token,  with the following POST data:

  • code – taken from the querystring sent back from google
  • redirect_uri – from your Google API console
  • client_id – from  your Google API console
  • scope –  empty
  • client_secret – from your Google API console
  • grant_type – set to authorization_code

This is the C# code I used to make this request  (My Access credentials removed)

string strToken = Request.QueryString[“code”];
System.Net.WebClient wc = new System.Net.WebClient();
string strExchange = “code={0}”;
strExchange += “&redirect_uri=…”;
strExchange += “&client_id=….”;
strExchange += “&scope=&”;
strExchange += “client_secret=….&grant_type=authorization_code”;
strExchange = string.Format(strExchange,strToken);
string strUrl = “https://accounts.google.com/o/oauth2/token&#8221;;
wc.Headers[System.Net.HttpRequestHeader.ContentType] = “application/x-www-form-urlencoded”;
string strHtml = wc.UploadString(strUrl, strExchange);

Returned, is a small piece of JSON in this format:

{ “access_token” : “ya29.AHES6ZTBNv8wBJFPnn7rMPvrHZseG6EUUvfYuiPFTx3TUT_zpYVEIQ”, “token_type” : “Bearer”, “expires_in” : 3600 }

One of the best ways to parse this JSON is to use the JavaScriptSerializer object built into .NET, this requires you to define a class that matches the JSON schema, like this:

public class RootObject
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
public string id_token { get; set; }
}

Then using the following code to convert the JSON into a “RootObject” object;

System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
RootObject ro = js.Deserialize<RootObject>(strHtml);

Once we have our RootObject, we can use the access_token to call Google APIs like so:

System.Net.WebClient wc2 = new System.Net.WebClient();
strUrl = “https://www.googleapis.com/analytics/v3/management/accounts&#8221;;
wc2.Headers.Add(“Authorization”,”Bearer ” + ro.access_token);
strHtml = wc2.DownloadString(strUrl);

This then returns the Google Analytics accounts associated with the authenticated Google user, in my case it is:

{
  "kind": "analytics#accounts",
  "username": "xxxx.xxxx@gmail.com",
  "totalResults": 1,
  "startIndex": 1,
  "itemsPerPage": 1000,
  "items": [
    {
      "id": "3658396",
      "kind": "analytics#account",
      "selfLink": "https:\/\/www.googleapis.com\/analytics\/v3\/management\/accounts\/3658396",
      "name": "www.outsourcetranslation.com",
      "created": "2008-02-17T13:58:09.000Z",
      "updated": "2011-07-07T22:34:55.677Z",
      "childLink": {
        "type": "analytics#webproperties",
        "href": "https:\/\/www.googleapis.com\/analytics\/v3\/management\/accounts\/3658396\/webproperties"
      }
    }
  ]
}

And there you have it, we’ve successfully used OAuth to authenticate a user against a Google API.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: