Implementing Yahoo OAuth 2.0 in CSharp and Asp.Net

Implementing Yahoo OAuth 2.0 in CSharp and Asp.Net

What is OAuth

OAuth is an open standard to authorize application to access user data from online servers without sharing user’s credentials. It is specifically designed to work in ‘Hypertext Transfer Protocol (HTTP)’. OAuth provides ‘access tokens’ to applications when the user gives approval, and through this access token the application can access the user’s data in online servers.

Today nearly all top service providers like amazon, google, yahoo, twitter , facebook etc support OAuth and allow applications to access users data stored in their servers (on the approval of the users). The first version of OAuth known as OAuth 1.0 became live in April 2010 then the next version i.e. OAuth 2.0 came in October 2012.

In this tutorial we will develop a small ‘Yahoo App’ which will implement Oauth 2.0. We would suggest you to read the Yahoo Oauth 2.0 guide at https://developer.yahoo.com/oauth2/guide/.

Here is the step by step procedure of implementation of Yahoo OAuth 2.0 in C# and Asp.Net-

1. Create Project where Yahoo OAuth will be Implemented

Firstly we will have to create ‘Consumer Key and Consumer Secret’ for our app so we will create a new project in our yahoo account, link is https://developer.yahoo.com/apps/.

Yahoo Create An App

Yahoo Create An App

In the ‘Create an Application’ form enter the following information:
  • a. Application Name – any name for your application
  • b. Application Type – Web-based
  • c. Description – any description for your application
  • d. Home Page URL – The domain URL of the website where the application will be placed
  • e. Access Scopes – choose ‘This app requires access to private user data.’
  • f. Callback Domain – The domain to which the application will return after authentication.
  • g. Select APIs for private user data access – Check ‘Contacts’ and ‘Read’ radio button.
  • h. Terms of Use – select the checkbox.

Finally click the ‘Create App’ button. It will create your project and you will be provided ‘Consumer Key & Consumer Secret’. Click on the consumer key to select it then copy it and save it for future use. Similarly save your consumer secret key.

Yahoo App Fields

Yahoo App Fields

We have used OAUTH in our Google Contacts API application. This application authenticates user with Google using OAUTH then exports all his Gmail Contacts.

2. Sending User to Authorize Access Page

Here you have to redirect the user to the yahoo page which will ask for their permission for your app. The URL is –
https://api.login.yahoo.com/oauth2/request_auth

Note that in the URL you have to pass the following 3 values in query string:
  • a. client_id – consumer key
  • b. redirect_url – the url to which yahoo redirects users after they authorize access to our app.
  • c. response_type – code
  • d. state – an optional parameter which will be appended to the redirect_url.
  • e. language – an optional parameter with default value ‘en-us’.
Yahoo Consumer Key and Consumer Secret

Yahoo Consumer Key and Consumer Secret

To implement it we will create a button in asp.net and in its click event redirect user to the above yahoo URL to authorize our app. The code below explains it –

Implementation

<asp:Button ID="yahooButton" Text="Implement Yahoo OAuth" runat="server" OnClick="yahooButton_Click" />

In ‘dataDiv’ we will show access token and other values send by Yahoo

<div id="dataDiv" runat="server"></div>
protected void yahooButton_Click(object sender, EventArgs e)
{
    string consumerKey = YOUR CONSUMER KEY;
    string returnUrl = "http://www.yogihosting.com/TutorialCode/YahooAuth2.0/yahoooauth2.aspx";
    
    /*Sending User To Authorize Access Page*/
    string url = "https://api.login.yahoo.com/oauth2/request_auth?client_id=" + consumerKey + "&redirect_uri=" + returnUrl + "&response_type=code&language=en-us";
    Response.Redirect(url);
    /*End*/
}

Note that here we are redirecting the user to the same page where our app is place. You can redirect the user to any URL of your choice.

3. Exchange Authorization Code for Access Token

Once the user authorizes our app he is redirected to the returnUrl with a querystring variable ‘code’ appended to it. The redirectUrl is the same which we have specified in the step above. The URL looks something like this –

http://www.yogihosting.com/TutorialCode/YahooAuth2.0/yahoooauth2.aspx?code=xyz

Now we have to request for ‘Access Token’ from yahoo. To do so we have to make an ‘HTTP POST’ request to the url – https://api.login.yahoo.com/oauth2/get_token

Include ‘Authorization: Basic Base64 encoding of consumerkey:consumersecret’ in the HTTP POST request header. The authorization code which we have just received also needs to be passed in the query string parameters.

Request Parameter to include in the ‘HTTP POST’ request:
  • a. client_id – consumer key
  • b. client_secret – consumer secret
  • c. redirect_url – the URL to which you want the user to redirect on successful return of access token
  • d. code – the authorization code received in the query string earlier
  • e. grant_type – authorization_code

Implementation

public void GetAccessToken()
{
    responseFromServer = responseFromServer.Substring(1, responseFromServer.Length - 2);
    string consumerKey = YOUR CONSUMER KEY;
    string consumerSecret = YOUR CONSUMER SECRET;

    string returnUrl = "http://www.yogihosting.com/TutorialCode/YahooOAuth2.0/yahoooauth2.aspx";
     
    /*Exchange authorization code for Access Token by sending Post Request*/
    Uri address = new Uri("https://api.login.yahoo.com/oauth2/get_token");

    // Create the web request  
    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

    // Set type to POST  
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    byte[] headerByte = System.Text.Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret);
    string headerString = System.Convert.ToBase64String(headerByte);
    request.Headers["Authorization"] = "Basic " + headerString;

    // Create the data we want to send  
    StringBuilder data = new StringBuilder();
    data.Append("client_id=" + consumerKey);
    data.Append("&client_secret=" + consumerSecret);
    data.Append("&redirect_uri=" + returnUrl);
    data.Append("&code=" + Request.QueryString["code"]);
    data.Append("&grant_type=authorization_code");

    // Create a byte array of the data we want to send  
    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

    // Set the content length in the request headers  
    request.ContentLength = byteData.Length;

    // Write data  
    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }

    // Get response  
    string responseFromServer = "";
    try
    {
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream  
            StreamReader reader = new StreamReader(response.GetResponseStream());
            responseFromServer = reader.ReadToEnd();
            ShowReceivedData(responseFromServer);
        }
    }
    catch (Exception ex)
    {
    }
}

We are capturing the ‘Authorization Code’ through Request.QueryString[“code”] and appending it to our StringBuilder variable. Once we received the Access Code response from the Yahoo server we are showing it in the div by calling the function ShowReceivedData (responseFromServer);

public void ShowReceivedData(string responseFromServer)
{
    responseFromServer = responseFromServer.Substring(1, responseFromServer.Length - 2);
    string accessToken = "", xoauthYahooGuid = "", refreshToken = "", tokenType = "", expiresIn = "";
    string[] splitByComma = responseFromServer.Split(',');
    foreach (string value in splitByComma)
    {
        if (value.Contains("access_token"))
        {
            string[] accessTokenSplitByColon = value.Split(':');
            accessToken = accessTokenSplitByColon[1].Replace('"'.ToString(), "");
        }
        else if (value.Contains("xoauth_yahoo_guid"))
        {
            string[] xoauthYahooGuidSplitByColon = value.Split(':');
            xoauthYahooGuid = xoauthYahooGuidSplitByColon[1].Replace('"'.ToString(), "");
        }
        else if (value.Contains("refresh_token"))
        {
            string[] refreshTokenSplitByColon = value.Split(':');
            refreshToken = refreshTokenSplitByColon[1].Replace('"'.ToString(), "");
        }
        else if (value.Contains("token_type"))
        {
            string[] tokenTypeSplitByColon = value.Split(':');
            tokenType = tokenTypeSplitByColon[1].Replace('"'.ToString(), "");
        }
        else if (value.Contains("expires_in"))
        {
            string[] expiresInSplitByColon = value.Split(':');
            expiresIn = expiresInSplitByColon[1].Replace('"'.ToString(), "");
        }
    }
    dataDiv.InnerHtml = "Access Token:- <b>" + accessToken + "</b><br/><br/> Refresh Token:- <b>" + refreshToken + "</b><br/><br/> XOauth Yahoo Guid:- <b>" + xoauthYahooGuid + "</b><br/><br/> Token Type:- <b>" + tokenType + "</b><br/><br/> Expires In:- <b>" + expiresIn + "</b>";
}
Response received from yahoo server:
  • a. access_token – the token through which you can make Yahoo API calls.
  • b. token_type – the access token type
  • c. expires_in – token lifetime in seconds
  • d. refresh_token – the refresh token that is used to get new token after the current token expires (as given in the ’expires_in’ parameter ).
  • e. xoauth_yahoo_guid – the GUID of the Yahoo user
GUID ?

GUID is a unique code given to every Yahoo user and is used to identify the user in different request.

Conclusion

Our application successfully received ‘Access Token’ from Yahoo hence Yahoo authorizes our app to do data retrieval, data addition and manipulation in the account of the person who has given permission to our app.

From here our app can make API calls to yahoo API and can easily communicate with large no of yahoo services available like Yahoo Contacts, Fantasy Sports, Mail Web Service and many more. You would like to Visit our article on Yahoo API where we export Yahoo contacts after authenticating user with OAUTH.

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on “WordPress, SEO, jQuery, HTML” and more.