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 stored in online servers.

Today nearly all top service providers like Amazon, Google, Yahoo, Twitter, Microsoft and Facebook support OAuth and allow applications to access users data stored in their servers. 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 I will develop a small Yahoo App which will implement OAuth 2.0. I would suggest you to read the Yahoo Oauth 2.0 guide at here.

Would you like to dig deep into the world of database programming with C#? Then you can check this series of tutorials on Entity Framework Core that help you to learn database programming within a few hours time.

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

1. Create Project where the Yahoo OAuth will be Implemented

Firstly I will have to create Consumer Key and Consumer Secret forthis app. So I create a new project in my yahoo account, link is https://developer.yahoo.com/apps/.

Yahoo Create An App
Next, in the Create an Application form enter:
  • 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 in your computer for future use. Similarly, do the same thing for the consumer secret key.

Yahoo App Fields
I have also used OAUTH in Google Contacts API application. This application authenticates user with Google using OAUTH then exports all the user’s 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 the 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

To implement it, I will create a button in Asp.Net and in it’s click event, redirect user to the above yahoo URL.

The code below explains it –

Implementation

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

In dataDiv I 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 = "https://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 I am 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 query string variable called code appended to the returnedUrl.

The redirectUrl is the same which we have specified in the step above. The URL looks something like this –

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

Now I have to request for Access Token from yahoo. To do so I 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 I 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 = "https://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)
    {
    }
}

I am capturing the Authorization Code through Request.QueryString[“code”], and appending it to our StringBuilder variable. Once I receive the Access Code response from the Yahoo server, I am then 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 and can easily communicate with large number of yahoo services available today like Yahoo Contacts, Fantasy Sports, Mail Web Service and many more.

You would like to Visit our article on Yahoo API where I export Yahoo contacts after authenticating user with Yahoo OAuth.

Download link:

DOWNLOAD

SHARE THIS ARTICLE

  • linkedin
  • reddit
yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee donate