Click here to Skip to main content
Click here to Skip to main content

2-Legged OAuth Authentication in .NET (C#)

By , 5 Jul 2012
 

Introduction

OAuth is an open standard for authorization. It allows users to approve application to act on their behalf without sharing their password. In this article, I am going to provide details about doing 2-Legged OAuth authentication in C# using OAuth.net library. You can read the full OAuth specification at: http://oauth.net/.

You could find a lot of examples and sample code on how to do it in Java. But I did not find a good enough example to do it in .NET. During one of my assignments, I had to spend considerable time to perform this, so I decided to write this article.

Background

OAuth provides two ways of authentication: 3 –Legged or 2–Legged authentication.

2- Legged authentication means that customer already has access to valid set of OAuth Consumer credentials (key & secret). You need to create a User’s OAuth Token request by signing the request as described in the OAuth Consumer Request Specification. The following OAuth article provides a very extensive detail about what all is required to perform an OAuth Consumer Request.

http://oauth.net/core/1.0/#sig_base_example

The main advantage of 2 legged authentication is that the user experience is seamless since no additional User interactions are required to initiate an API session.

Using the code

The code is self explanatory. Use the attached ServiceProvider class to instantiate an OAuth Request. You can use PostData\GetData methods to perform POST\GET requests, respectively.

ServiceProvider provider = new ServiceProvider(serviceUrl, consumerKey, secret);
//Perform a POST requestString response = provider.PostData("application/json", data);

The GenerateRequest function shows how to sign an OAuth Request.   

private HttpWebRequest GenerateRequest(string contentType, string requestMethod)
{
    var ts = UnixTime.ToUnixTime(DateTime.Now);
    //Create the needed OAuth Parameters.
    //Refer - http://oauth.net/core/1.0/#sig_base_example
    var param = new OAuthParameters() {
    ConsumerKey = _consumerKey,
        SignatureMethod = SigningProvider.SignatureMethod,
        Version = Constants.Version1_0,
        Nonce = NonceProvider.GenerateNonce(ts),
        Timestamp = ts.ToString(),
    };
    //Generate Signature Hash
    var signatureBase = SignatureBase.Create(requestMethod.ToUpper(), _serviceProviderUri, param);
    //Set Signature Hash as one of the OAuth Parameter
    param.Signature = SigningProvider.ComputeSignature(signatureBase, _consumerSecret, null);
    var httpWebRequest = (HttpWebRequest)WebRequest.Create(_serviceProviderUri);
    httpWebRequest.Method = requestMethod;
    httpWebRequest.ContentType = contentType;
    httpWebRequest.Timeout = RequestTimeOut;
    //Add the OAuth Parameters to Authorization Header of Request
    httpWebRequest.Headers.Add(Constants.AuthorizationHeaderParameter, param.ToHeaderFormat());
    return httpWebRequest;
}

Dependencies

The code is dependent on OAuth.Net library (http://code.google.com/p/oauth-dot-net/). You will need to add a reference to the OAuth libraries to compile the code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sumit Chawla
Software Developer (Senior)
United States United States
Member
I am currently working as a Senior Software Developer. My primary skills include .NET, WPF,MSSQL,and C++. I have also worked in ASP.NET, XML, XSL, JavaScript,and Web Automation.
I love to solve problems,and love to do programming. In my idle time i love to explore new technologies and domains.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionHow to post method detailsmemberAmshumanth Sirga18 Jan '13 - 20:17 
Hi,
 
Thanks for the code.
I am using Moo.com API with POST method. I am getting Http 417 expectation failed error. It means I am able to access the server but it has some problem in understanding my request. How do we pass method details like method name, parameters while POST. Please let me know.
 
Thanks
Amshumanth Sirga
QuestionHow can use this code in to connect to dropbox accountmemberraosrini22 Nov '12 - 20:33 
HI,
how can i use this code to connect to my dropbox account(http://www.dropbox.com) without building the web based url approach i have api key, api secret what extra things i need have ,i need to perform CRUD actions from my web application is it possibel without user involvement with this code
QuestionUsing Code and oAuth .NET library. It gives an Errormemberha_haseebahmad19 Sep '12 - 2:13 
I am using the attach code using oAuth.NET library but It gives an Error msg.
 
WebException while reading response - The remote server returned an error: (400) Bad Request.
 
I have the information below
 
Consumer Name:
Client Tenent:
Secret Key:
URL:
 
See my code below and please reply.
 
ServiceProvider oServerProvider = new ServiceProvider(strURL, strSecretKey, strConsumerName);
string strResponse = oServerProvider.GetData();
 
Regards,
HA.
AnswerRe: Using Code and oAuth .NET library. It gives an ErrormemberSumit Chawla19 Sep '12 - 7:14 
I think you are passing parameters to constructor in wrong order. Try following:
ServiceProvider oServerProvider = new ServiceProvider(strURL,strConsumerName,strSecretKey);

AnswerRe: Using Code and oAuth .NET library. It gives an ErrormemberSumit Chawla11 Oct '12 - 14:03 
I think you are passing strSecretKey and steConsumerName in wrong order. Reverse the order and try
GeneralMy vote of 5memberKashif_Imran30 Jul '12 - 12:44 
Helped me a lot. Thanks.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 5 Jul 2012
Article Copyright 2012 by Sumit Chawla
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid