Exemplo n.º 1
0
        private Tuple <HttpWebRequest, string> PrepareOAuthRequest(string oauthSource, string serverRSAExponent, string serverRSAModulus, string challenge)
        {
#if !SILVERLIGHT
            var authRequest = (HttpWebRequest)WebRequest.Create(oauthSource);
#else
            var authRequest = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri(oauthSource));
#endif
            authRequest.Headers["grant_type"] = "client_credentials";
            authRequest.Accept = "application/json;charset=UTF-8";
            authRequest.Method = "POST";

            if (!string.IsNullOrEmpty(serverRSAExponent) && !string.IsNullOrEmpty(serverRSAModulus) && !string.IsNullOrEmpty(challenge))
            {
                var parameters = Tuple.Create(OAuthHelper.ParseBytes(serverRSAExponent), OAuthHelper.ParseBytes(serverRSAModulus));

                var apiKeyParts = apiKey.Split(new[] { '/' }, StringSplitOptions.None);

                if (apiKeyParts.Length > 2)
                {
                    apiKeyParts[1] = string.Join("/", apiKeyParts.Skip(1));
                }

                if (apiKeyParts.Length < 2)
                {
                    throw new InvalidOperationException("Invalid API key");
                }

                var apiKeyName = apiKeyParts[0].Trim();
                var apiSecret  = apiKeyParts[1].Trim();


                var data = OAuthHelper.DictionaryToString(new Dictionary <string, string>
                {
                    { OAuthHelper.Keys.RSAExponent, serverRSAExponent },
                    { OAuthHelper.Keys.RSAModulus, serverRSAModulus },
                    {
                        OAuthHelper.Keys.EncryptedData,
                        OAuthHelper.EncryptAssymetric(parameters, OAuthHelper.DictionaryToString(new Dictionary <string, string>
                        {
                            { OAuthHelper.Keys.APIKeyName, apiKeyName },
                            { OAuthHelper.Keys.Challenge, challenge },
                            {
                                OAuthHelper.Keys.Response,
                                OAuthHelper.Hash(string.Format(OAuthHelper.Keys.ResponseFormat, challenge, apiSecret))
                            }
                        }))
                    }
                });

                return(Tuple.Create(authRequest, data));
            }
            authRequest.ContentLength = 0;
            return(Tuple.Create(authRequest, (string)null));
        }