Thursday, August 7, 2008

AUTHENTICATE oAuth SIGNATURE in C#(orkut Apps)

From last few days I was stucked in a problem during developing an open social app on orkut for my company.
I had to authenticate the oauth request from orkut app in my C# App.
The request was having data both in querystring and post(form) .
Posted many places but not found any exact Solution.
Cople of solutions were there
http://www.experts-exchange.com/Software/Server_Software/Web_Servers/Apache/Q_23238711.html

http://eran.sandler.co.il/2007/10/17/oauth-c-very-basic-library/

But they only able to autheticate get data request in case of post they were failing.

Even on OAUTH site they have given only the oAuth class that is not useful in case of authentication.


but at last my hit and trail with this code returend me the solution. that was very silly problem Here is the solution.

function bool Auth(httpRequest request)
{
        if (!string.IsNullOrEmpty(request["oauth_signature"]))
        {
            X509Certificate2 cert = new X509Certificate2(Encoding.ASCII.GetBytes(certificate), "", X509KeyStorageFlags.MachineKeySet);
            NameValueCollection queryString = request.QueryString;
            string signature = request["oauth_signature"];
            Base64Decoder decoder = new Base64Decoder(signature.ToCharArray());

            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key;
            OAuth.OAuthBase asd = Snew OAuth.OAuthBase();
            string url = request.Url.ToString();
            foreach (string name in request.Form)
                url += "&" + name + "=" + request.Form[name];
            Uri reqURi = new Uri(url);
            string signatureBase = asd.GenerateSignatureBase(reqURi, request["oauth_consumer_key"], "", "",
                request.ServerVariables["REQUEST_METHOD"].ToUpper(), request["oauth_timestamp"],
                request["oauth_nonce"], request["oauth_signature_method"], out urvl, out urlNPAM);
            bool rtn = rsa.VerifyData(
                Encoding.ASCII.GetBytes(signatureBase), "SHA1", decoder.GetDecoded());
           return rtn;
        }
}