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.
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.
Here is the step by step procedure of implementation of Yahoo OAuth 2.0 in C# and Asp.Net-
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/.
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.
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
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 –
<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.
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.
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>";
}
GUID is a unique code given to every Yahoo user and is used to identify the user in different request.
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.
Download link: