/// <summary>
 /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
 /// <see cref="IAuthenticator" /> for the purpose of requesting an
 /// unauthorized request token.
 /// </summary>
 /// <param name="method">The HTTP method for the intended request</param>
 /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
 /// <a href="http://oauth.net/core/1.0#anchor9"/>
 /// <returns></returns>
 public OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParameterCollection parameters)
 {
     ValidateTokenRequestState();
     if (parameters == null)
     {
         parameters = new WebParameterCollection();
     }
     var timestamp = CreateTimestampFunc();
     var nonce = OAuthTools.GetNonce();
     AddAuthParameters(parameters, timestamp, nonce);
     var signatureBase = OAuthTools.ConcatenateRequestElements(method, RequestTokenUrl, parameters);
     var signature = OAuthTools.GetSignature(SignatureProvider, SignatureTreatment, signatureBase, ConsumerSecret);
     var info = new OAuthWebQueryInfo
     {
         WebMethod = method,
         ParameterHandling = ParameterHandling,
         ConsumerKey = ConsumerKey,
         SignatureMethod = SignatureProvider.Id,
         SignatureTreatment = SignatureTreatment,
         Signature = signature,
         Timestamp = timestamp,
         Nonce = nonce,
         Version = Version ?? "1.0",
         Callback = OAuthTools.UrlEncodeRelaxed(CallbackUrl ?? ""),
         TokenSecret = TokenSecret,
         ConsumerSecret = ConsumerSecret
     };
     return info;
 }
        /// <summary>
        /// Creates a request elements concatentation value to send with a request.
        /// This is also known as the signature base.
        /// </summary>
        /// <a href="http://oauth.net/core/1.0#rfc.section.9.1.3"/>
        /// <a href="http://oauth.net/core/1.0#sig_base_example"/>
        /// <param name="method">The request's HTTP method type</param>
        /// <param name="url">The request URL</param>
        /// <param name="parameters">The request's parameters</param>
        /// <returns>A signature base string</returns>
        public static string ConcatenateRequestElements(string method, string url, WebParameterCollection parameters)
        {
            var sb = new StringBuilder();

            // Separating &'s are not URL encoded
            var requestMethod     = string.Concat(method.ToUpper(), "&");
            var requestUrl        = string.Concat(UrlEncodeRelaxed(ConstructRequestUrl(new Uri(url))), "&");
            var requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters));

            sb.Append(requestMethod);
            sb.Append(requestUrl);
            sb.Append(requestParameters);
            return(sb.ToString());
        }
        /// <summary>
        /// Sorts a <see cref="WebParameterCollection"/> by name, and then value if equal.
        /// </summary>
        /// <param name="parameters">A collection of parameters to sort</param>
        /// <returns>A sorted parameter collection</returns>
        public static WebParameterCollection SortParametersExcludingSignature(WebParameterCollection parameters)
        {
            var copy       = new WebParameterCollection(parameters);
            var exclusions = copy.Where(n => string.Equals(n.Name, "oauth_signature", StringComparison.OrdinalIgnoreCase));

            copy.RemoveAll(exclusions);
            copy.ForEach(p => { p.Name = UrlEncodeStrict(p.Name); p.Value = UrlEncodeStrict(p.Value); });
            copy.Sort(
                (x, y) =>
                string.CompareOrdinal(x.Name, y.Name) != 0
            ? string.CompareOrdinal(x.Name, y.Name)
            : string.CompareOrdinal(x.Value, y.Value));
            return(copy);
        }
        private void AddXAuthParameters(ICollection <WebParameter> parameters, string timestamp, string nonce)
        {
            var authParameters = new WebParameterCollection
            {
                new WebParameter("x_auth_username", ClientUsername, WebParameterType.Internal),
                new WebParameter("x_auth_password", ClientPassword, WebParameterType.Internal),
                new WebParameter("x_auth_mode", "client_auth", WebParameterType.Internal),
                new WebParameter("oauth_consumer_key", ConsumerKey, WebParameterType.Internal),
                new WebParameter("oauth_signature_method", SignatureProvider.Id, WebParameterType.Internal),
                new WebParameter("oauth_timestamp", timestamp, WebParameterType.Internal),
                new WebParameter("oauth_nonce", nonce, WebParameterType.Internal),
                new WebParameter("oauth_version", Version ?? "1.0", WebParameterType.Internal)
            };

            foreach (var authParameter in authParameters)
            {
                parameters.Add(authParameter);
            }
        }
Exemple #5
0
        private void AddXAuthParameters(ICollection <WebPair> parameters, string timestamp, string nonce)
        {
            var authParameters = new WebParameterCollection
            {
                new WebPair("x_auth_username", ClientUsername),
                new WebPair("x_auth_password", ClientPassword),
                new WebPair("x_auth_mode", "client_auth"),
                new WebPair("oauth_consumer_key", ConsumerKey),
                new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
                new WebPair("oauth_timestamp", timestamp),
                new WebPair("oauth_nonce", nonce),
                new WebPair("oauth_version", Version ?? "1.0")
            };

            foreach (var authParameter in authParameters)
            {
                parameters.Add(authParameter);
            }
        }
        public OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, string url)
        {
            ValidateProtectedResourceState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }

            // Include url parameters in query pool
            var uri           = new Uri(url);
            var urlParameters = uri.Query.ParseQueryString();

            foreach (var parameter in urlParameters.Keys)
            {
                parameters.Add(new WebParameter(parameter, urlParameters[parameter], WebParameterType.Query));
            }
            var timestamp = CreateTimestampFunc();
            var nonce     = OAuthTools.GetNonce(RandomNumberGenerator);

            AddAuthParameters(parameters, timestamp, nonce);
            var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters);
            var signature     = OAuthTools.GetSignature(
                SignatureProvider, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret);
            var info = new OAuthWebQueryInfo
            {
                WebMethod          = method,
                ParameterHandling  = ParameterHandling,
                ConsumerKey        = ConsumerKey,
                Token              = Token,
                SignatureMethod    = SignatureProvider.Id,
                SignatureTreatment = SignatureTreatment,
                Signature          = signature,
                Timestamp          = timestamp,
                Nonce              = nonce,
                Version            = Version ?? "1.0",
                Callback           = CallbackUrl,
                ConsumerSecret     = ConsumerSecret,
                TokenSecret        = TokenSecret
            };

            return(info);
        }
 /// <summary>
 /// Sorts a collection of key-value pairs by name, and then value if equal,
 /// concatenating them into a single string. This string should be encoded
 /// prior to, or after normalization is run.
 /// </summary>
 /// <a href="http://oauth.net/core/1.0#rfc.section.9.1.1"/>
 /// <param name="parameters"></param>
 /// <returns></returns>
 public static string NormalizeRequestParameters(WebParameterCollection parameters)
 {
     var copy = SortParametersExcludingSignature(parameters);
     var concatenated = copy.Concatenate("=", "&");
     return concatenated;
 }
 /// <summary>
 /// Sorts a <see cref="WebParameterCollection"/> by name, and then value if equal.
 /// </summary>
 /// <param name="parameters">A collection of parameters to sort</param>
 /// <returns>A sorted parameter collection</returns>
 public static WebParameterCollection SortParametersExcludingSignature(WebParameterCollection parameters)
 {
     var copy = new WebParameterCollection(parameters);
     var exclusions = copy.Where(n => string.Equals(n.Name, "oauth_signature", StringComparison.OrdinalIgnoreCase));
     copy.RemoveAll(exclusions);
     copy.ForEach(p => { p.Name = UrlEncodeStrict(p.Name); p.Value = UrlEncodeStrict(p.Value); });
     copy.Sort(
     (x, y) =>
     string.CompareOrdinal(x.Name, y.Name) != 0
     ? string.CompareOrdinal(x.Name, y.Name)
     : string.CompareOrdinal(x.Value, y.Value));
     return copy;
 }
 private void AddXAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce)
 {
     var authParameters = new WebParameterCollection
     {
         new WebPair("x_auth_username", ClientUsername),
         new WebPair("x_auth_password", ClientPassword),
         new WebPair("x_auth_mode", "client_auth"),
         new WebPair("oauth_consumer_key", ConsumerKey),
         new WebPair("oauth_signature_method", SignatureProvider.Id),
         new WebPair("oauth_timestamp", timestamp),
         new WebPair("oauth_nonce", nonce),
         new WebPair("oauth_version", Version ?? "1.0")
     };
     foreach (var authParameter in authParameters)
     {
         parameters.Add(authParameter);
     }
 }
 public OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, string url)
 {
     ValidateProtectedResourceState();
     if (parameters == null)
     {
         parameters = new WebParameterCollection();
     }
     // Include url parameters in query pool
     var uri = new Uri(url);
     var urlParameters = uri.Query.ParseQueryString();
     foreach (var parameter in urlParameters.Keys)
     {
         switch (method.ToUpperInvariant())
         {
             case "POST":
                 parameters.Add(new HttpPostParameter(parameter, urlParameters[parameter]));
                 break;
             default:
                 parameters.Add(parameter, urlParameters[parameter]);
                 break;
         }
     }
     var timestamp = CreateTimestampFunc();
     var nonce = OAuthTools.GetNonce();
     AddAuthParameters(parameters, timestamp, nonce);
     var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters);
     var signature = OAuthTools.GetSignature(
     SignatureProvider, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret);
     var info = new OAuthWebQueryInfo
     {
         WebMethod = method,
         ParameterHandling = ParameterHandling,
         ConsumerKey = ConsumerKey,
         Token = Token,
         SignatureMethod = SignatureProvider.Id,
         SignatureTreatment = SignatureTreatment,
         Signature = signature,
         Timestamp = timestamp,
         Nonce = nonce,
         Version = Version ?? "1.0",
         Callback = CallbackUrl,
         ConsumerSecret = ConsumerSecret,
         TokenSecret = TokenSecret
     };
     return info;
 }
 /// <summary>
 /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
 /// <see cref="IAuthenticator" /> for the purpose of exchanging user credentials
 /// for an access token authorized by the user at the Service Provider site.
 /// </summary>
 /// <param name="method">The HTTP method for the intended request</param>
 /// <a href="http://tools.ietf.org/html/draft-dehora-farrell-oauth-accesstoken-creds-00#section-4"/>
 /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
 public OAuthWebQueryInfo BuildClientAuthAccessTokenInfo(string method, WebParameterCollection parameters)
 {
     ValidateClientAuthAccessRequestState();
     if (parameters == null)
     {
         parameters = new WebParameterCollection();
     }
     var uri = new Uri(AccessTokenUrl);
     var timestamp = CreateTimestampFunc();
     var nonce = OAuthTools.GetNonce();
     AddXAuthParameters(parameters, timestamp, nonce);
     var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters);
     var signature = OAuthTools.GetSignature(SignatureProvider, SignatureTreatment, signatureBase, ConsumerSecret);
     var info = new OAuthWebQueryInfo
     {
         WebMethod = method,
         ParameterHandling = ParameterHandling,
         ClientMode = "client_auth",
         ClientUsername = ClientUsername,
         ClientPassword = ClientPassword,
         ConsumerKey = ConsumerKey,
         SignatureMethod = SignatureProvider.Id,
         SignatureTreatment = SignatureTreatment,
         Signature = signature,
         Timestamp = timestamp,
         Nonce = nonce,
         Version = Version ?? "1.0",
         TokenSecret = TokenSecret,
         ConsumerSecret = ConsumerSecret
     };
     return info;
 }
Exemple #12
0
 public virtual void AddRange(WebParameterCollection collection)
 {
     AddCollection(collection);
 }
 /// <summary>
 /// Generates a <see cref="OAuthWebQueryInfo"/> instance to pass to an
 /// <see cref="IAuthenticator" /> for the purpose of exchanging a request token
 /// for an access token authorized by the user at the Service Provider site.
 /// </summary>
 /// <param name="method">The HTTP method for the intended request</param>
 /// <a href="http://oauth.net/core/1.0#anchor9"/>
 /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
 public OAuthWebQueryInfo BuildAccessTokenInfo(string method, WebParameterCollection parameters)
 {
     ValidateAccessRequestState();
     if (parameters == null)
     {
         parameters = new WebParameterCollection();
     }
     var uri = new Uri(AccessTokenUrl);
     var timestamp = CreateTimestampFunc();
     var nonce = OAuthTools.GetNonce(RandomNumberGenerator);
     AddAuthParameters(parameters, timestamp, nonce);
     var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters);
     var signature = OAuthTools.GetSignature(SignatureProvider, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret);
     var info = new OAuthWebQueryInfo
     {
         WebMethod = method,
         ParameterHandling = ParameterHandling,
         ConsumerKey = ConsumerKey,
         Token = Token,
         SignatureMethod = SignatureProvider.Id,
         SignatureTreatment = SignatureTreatment,
         Signature = signature,
         Timestamp = timestamp,
         Nonce = nonce,
         Version = Version ?? "1.0",
         Verifier = Verifier,
         Callback = CallbackUrl,
         TokenSecret = TokenSecret,
         ConsumerSecret = ConsumerSecret,
     };
     return info;
 }
        private string GetAuthorizationHeader(WebParameterCollection parameters)
        {
            var sb = new StringBuilder();
            if (!string.IsNullOrEmpty(Realm))
            {
                sb.Append(string.Format("realm=\"{0}\",", OAuthTools.UrlEncodeRelaxed(Realm)));
            }

            parameters.Sort((l, r) => string.Compare(l.Name, r.Name, StringComparison.Ordinal));
            var parameterCount = 0;
            var oathParameters = parameters.Where(
                parameter => !string.IsNullOrEmpty(parameter.Name)
                             && !string.IsNullOrEmpty(parameter.Value)
                             && (parameter.Name.StartsWith("oauth_") || parameter.Name.StartsWith("x_auth_"))).ToList();
            foreach (var parameter in oathParameters)
            {
                parameterCount++;
                var format = parameterCount < oathParameters.Count ? "{0}=\"{1}\"," : "{0}=\"{1}\"";
                sb.Append(string.Format(format, parameter.Name, parameter.Value));
            }

            var authorization = sb.ToString();
            return string.Format("{0} {1}", AuthenticationMethod, authorization);
        }
        private void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            var url = client.BuildUri(request, false).ToString();
            OAuthWebQueryInfo oauth;
            var method = request.Method.ToString();
            var parameters = new WebParameterCollection();

            // include all GET and POST parameters before generating the signature
            // according to the RFC 5849 - The OAuth 1.0 Protocol
            // http://tools.ietf.org/html/rfc5849#section-3.4.1
            // if this change causes trouble we need to introduce a flag indicating the specific OAuth implementation level,
            // or implement a seperate class for each OAuth version
            var useMultiPart = request.ContentCollectionMode == ContentCollectionMode.MultiPart
                               || (request.ContentCollectionMode == ContentCollectionMode.MultiPartForFileParameters
                                   && (client.DefaultParameters.GetFileParameters().Any() || request.Parameters.GetFileParameters().Any()));

            var requestParameters = client.MergeParameters(request).OtherParameters.AsEnumerable();
            var effectiveMethod = client.GetEffectiveHttpMethod(request);
            if (effectiveMethod == Method.GET)
            {
                requestParameters = requestParameters.Where(x => x.Type == ParameterType.GetOrPost || x.Type == ParameterType.QueryString);
                foreach (var p in requestParameters)
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Query));
                }
            }
            else if (!useMultiPart && effectiveMethod == Method.POST)
            {
                foreach (var p in requestParameters.Where(x => x.Type == ParameterType.QueryString))
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Query));
                }
                foreach (var p in requestParameters.Where(x => x.Type == ParameterType.GetOrPost))
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Post));
                }
            }
            else
            {
                // if we are sending a multipart request, only the "oauth_" parameters should be included in the signature
                foreach (var p in requestParameters.Where(p => p.Name.StartsWith("oauth_", StringComparison.Ordinal)))
                {
                    parameters.Add(new WebParameter(p.Name, p.Value.ToString(), WebParameterType.Internal));
                }
            }

            switch (Type)
            {
                case OAuthType.RequestToken:
                    workflow.RequestTokenUrl = url;
                    oauth = workflow.BuildRequestTokenInfo(method, parameters);
                    break;
                case OAuthType.AccessToken:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ClientAuthentication:
                    workflow.AccessTokenUrl = url;
                    oauth = workflow.BuildClientAuthAccessTokenInfo(method, parameters);
                    break;
                case OAuthType.ProtectedResource:
                    oauth = workflow.BuildProtectedResourceInfo(method, parameters, url);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }

            switch (ParameterHandling)
            {
                case OAuthParameterHandling.HttpAuthorizationHeader:
                    parameters.Add("oauth_signature", oauth.Signature, WebParameterType.Internal);
                    request.AddHeader("Authorization", GetAuthorizationHeader(parameters));
                    break;
                case OAuthParameterHandling.UrlOrPostParameters:
                    parameters.Add("oauth_signature", oauth.Signature, WebParameterType.Internal);
                    foreach (var parameter in parameters.Where(
                        parameter => !string.IsNullOrEmpty(parameter.Name)
                                     && (parameter.Name.StartsWith("oauth_") || parameter.Name.StartsWith("x_auth_"))))
                    {
                        var v = parameter.Value;
                        v = Uri.UnescapeDataString(v.Replace('+', ' '));
                        request.AddOrUpdateParameter(parameter.Name, v);
                    }

                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
 /// <summary>
 /// Sorts a <see cref="WebParameterCollection"/> by name, and then value if equal.
 /// </summary>
 /// <param name="parameters">A collection of parameters to sort</param>
 /// <returns>A sorted parameter collection</returns>
 public static WebParameterCollection SortParametersExcludingSignature(WebParameterCollection parameters)
 {
     var copy = new WebParameterCollection(parameters.Select(x => new WebParameter(x.Name, x.Value, x.Type)));
     var exclusions = copy.Where(n => string.Equals(n.Name, "oauth_signature", StringComparison.OrdinalIgnoreCase));
     copy.RemoveAll(exclusions);
     copy.ForEach(p =>
     {
         p.Name = UrlEncodeStrict(p.Name);
         if (p.Type == WebParameterType.Query)
         {
             // Parameter provided by the user
             p.Value = _escapeUtility.Escape(p.Value, _encoding, UrlEscapeFlags.AllowLikeWebRequest);
         }
         else
         {
             // Authorization or POST parameter
             p.Value = UrlEncodeStrict(p.Value);
         }
     });
     copy.Sort(
     (x, y) =>
     string.CompareOrdinal(x.Name, y.Name) != 0
     ? string.CompareOrdinal(x.Name, y.Name)
     : string.CompareOrdinal(x.Value, y.Value));
     return copy;
 }
        /// <summary>
        /// Creates a request elements concatentation value to send with a request.
        /// This is also known as the signature base.
        /// </summary>
        /// <a href="http://oauth.net/core/1.0#rfc.section.9.1.3"/>
        /// <a href="http://oauth.net/core/1.0#sig_base_example"/>
        /// <param name="method">The request's HTTP method type</param>
        /// <param name="url">The request URL</param>
        /// <param name="parameters">The request's parameters</param>
        /// <returns>A signature base string</returns>
        public static string ConcatenateRequestElements(string method, string url, WebParameterCollection parameters)
        {
            var sb = new StringBuilder();

            // Separating &'s are not URL encoded
            var requestMethod = string.Concat(method.ToUpper(), "&");
            var requestUrl = string.Concat(UrlEncodeRelaxed(ConstructRequestUrl(new Uri(url))), "&");
            var requestParameters = UrlEncodeRelaxed(NormalizeRequestParameters(parameters));
            sb.Append(requestMethod);
            sb.Append(requestUrl);
            sb.Append(requestParameters);
            return sb.ToString();
        }
 private void AddAuthParameters(ICollection<WebPair> parameters, string timestamp, string nonce)
 {
     var authParameters = new WebParameterCollection
     {
         new WebPair("oauth_consumer_key", ConsumerKey),
         new WebPair("oauth_nonce", nonce),
         new WebPair("oauth_signature_method", SignatureProvider.Id),
         new WebPair("oauth_timestamp", timestamp),
         new WebPair("oauth_version", Version ?? "1.0")
     };
     if (!string.IsNullOrEmpty(Token))
     {
         authParameters.Add(new WebPair("oauth_token", Token));
     }
     if (!string.IsNullOrEmpty(CallbackUrl))
     {
         authParameters.Add(new WebPair("oauth_callback", CallbackUrl));
     }
     if (!string.IsNullOrEmpty(Verifier))
     {
         authParameters.Add(new WebPair("oauth_verifier", Verifier));
     }
     if (!string.IsNullOrEmpty(SessionHandle))
     {
         authParameters.Add(new WebPair("oauth_session_handle", SessionHandle));
     }
     foreach (var authParameter in authParameters)
     {
         parameters.Add(authParameter);
     }
 }