예제 #1
0
        private string GetAuthorizationHeader(WebPairCollection parameters)
        {
            var sb = new StringBuilder("OAuth ");

            if (!Realm.IsNullOrBlank())
            {
                sb.Append("realm=\"{0}\",".FormatWith(OAuthTools.UrlEncodeRelaxed(Realm)));
            }

            parameters.Sort((l, r) => l.Name.CompareTo(r.Name));

            var parameterCount = 0;
            var oathParameters =
                parameters.Where(p => !p.Name.IsNullOrBlank() &&
                                 !p.Value.IsNullOrBlank() &&
                                 (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_")))
                .ToList();

            foreach (var parameter in oathParameters)
            {
                parameterCount++;

                var format = parameterCount < oathParameters.Count
                    ? "{0}=\"{1}\","
                    : "{0}=\"{1}\"";

                sb.Append(format.FormatWith(parameter.Name, parameter.Value));
            }

            var authorization = sb.ToString();

            return(authorization);
        }
예제 #2
0
 public WebPair(string name, string value, bool encode = false)
 {
     Name     = name;
     Value    = value;
     WebValue = encode ? OAuthTools.UrlEncodeRelaxed(value) : value;
     Encode   = encode;
 }
예제 #3
0
        private string GetAuthorizationHeader(WebPairCollection parameters)
        {
            var sb = new StringBuilder("OAuth ");

            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(authorization);
        }
예제 #4
0
        public void Can_url_encode_with_uppercase_hexadecimals()
        {
            const string expected = "What%20century%20is%20this%3F";
            var          actual   = OAuthTools.UrlEncodeRelaxed("What century is this?");

            Assert.AreEqual(expected, actual);
            Console.WriteLine(actual);
        }
예제 #5
0
        public void Can_relax_url_encode_complex_string()
        {
            // Doesn't URL encode ! or * in this sequence
            const string expected = "!%3F%22%3B%3A%3C%3E%5C%5C%7C%60%23%24%25%5E%26*%2B-_%7B%7D%5B%5D";
            const string sequence = @"!?"";:<>\\|`#$%^&*+-_{}[]";

            var actual = OAuthTools.UrlEncodeRelaxed(sequence);

            Assert.AreEqual(expected, actual);
        }
예제 #6
0
        public void Use_RFC_3986_Encoding_For_Auth_Signature_Base()
        {
            // reserved characters for 2396 and 3986
            var reserved2396Characters           = new[] { ";", "/", "?", ":", "@", "&", "=", "+", "$", "," }; // http://www.ietf.org/rfc/rfc2396.txt
            var additionalReserved3986Characters = new[] { "!", "*", "'", "(", ")" };                          // http://www.ietf.org/rfc/rfc3986.txt
            var reservedCharacterString          = string.Join(string.Empty, reserved2396Characters.Union(additionalReserved3986Characters));

            // act
            var escapedString = OAuthTools.UrlEncodeRelaxed(reservedCharacterString);

            // assert
            Assert.Equal("%3B%2F%3F%3A%40%26%3D%2B%24%2C%21%2A%27%28%29", escapedString);
        }
        private string GetAuthorizationHeader(WebPairCollection parameters)
        {
            StringBuilder stringBuilder = new StringBuilder("OAuth ");

            if (!Realm.IsNullOrBlank())
            {
                stringBuilder.Append("realm=\"{0}\",".FormatWith(OAuthTools.UrlEncodeRelaxed(Realm)));
            }
            parameters.Sort((WebPair l, WebPair r) => l.Name.CompareTo(r.Name));
            int            num  = 0;
            List <WebPair> list = (from parameter in parameters
                                   where !parameter.Name.IsNullOrBlank() && !parameter.Value.IsNullOrBlank() && (parameter.Name.StartsWith("oauth_") || parameter.Name.StartsWith("x_auth_"))
                                   select parameter).ToList();

            foreach (WebPair item in list)
            {
                num++;
                string format = (num < list.Count) ? "{0}=\"{1}\"," : "{0}=\"{1}\"";
                stringBuilder.Append(format.FormatWith(item.Name, item.Value));
            }
            return(stringBuilder.ToString());
        }
예제 #8
0
 public void UrlEncodeRelaxed_Throws_ArgumentNull_On_Null_String()
 {
     Assert.Throws <ArgumentNullException>(() => OAuthTools.UrlEncodeRelaxed(null));
 }
예제 #9
0
        public void UrlEncodeRelaxed_Encodes_Uri_Properly(string uri, string expected)
        {
            string encodedUri = OAuthTools.UrlEncodeRelaxed(uri);

            Assert.Equal(expected, encodedUri);
        }
예제 #10
0
        public void Authenticate(IRestClient client, IRestRequest request)
        {
            var url = client.BuildUri(request).ToString();

            // add body xauth arguments
            var arguments = new Dictionary <string, object>();

            if (string.IsNullOrWhiteSpace(Token))
            {
                arguments.Add("x_auth_username", Username);
                arguments.Add("x_auth_mode", "client_auth");
                arguments.Add("x_auth_password", Password);

                foreach (var item in arguments)
                {
                    request.AddParameter(item.Key, item.Value);
                }
            }
            else
            {
                foreach (var parameter in request.Parameters)
                {
                    arguments.Add(parameter.Name, parameter.Value);
                }
            }

            var nonce           = OAuthTools.GetNonce();
            var signatureMethod = "HMAC-SHA1";
            var timeStamp       = OAuthTools.GetTimestamp();
            var version         = "1.0";

            var oauthArguments = new Dictionary <string, string>();

            oauthArguments.Add("oauth_signature_method", signatureMethod);
            oauthArguments.Add("oauth_nonce", nonce);
            oauthArguments.Add("oauth_consumer_key", ConsumerKey);
            oauthArguments.Add("oauth_timestamp", timeStamp);
            oauthArguments.Add("oauth_version", version);
            if (!string.IsNullOrWhiteSpace(Token))
            {
                oauthArguments.Add("oauth_token", Token);
            }

            var mergedArguments = new Dictionary <string, object>(arguments);

            foreach (var item in oauthArguments)
            {
                mergedArguments.Add(item.Key, item.Value);
            }

            mergedArguments = mergedArguments.OrderBy(i => i.Key).ToDictionary(pair => pair.Key, pair => pair.Value);

            var signatureBase = String.Format("{0}&{1}&", Method.POST, OAuthTools.UrlEncodeRelaxed(url));

            foreach (var item in mergedArguments)
            {
                var    encodedKey = OAuthTools.UrlEncodeRelaxed(item.Key);
                string encodedValue;
                if (item.Value != null)
                {
                    encodedValue = OAuthTools.UrlEncodeRelaxed(item.Value.ToString());
                }
                else
                {
                    encodedValue = string.Empty;
                }
                signatureBase += String.Format("{0}%3D{1}%26", encodedKey, encodedValue);
            }

            signatureBase = signatureBase.Substring(0, signatureBase.Length - 3);
            signatureBase = signatureBase.Replace("%40", "%2540"); // ugly hack for now...

            var signature = OAuthTools.GetSignature(signatureBase, ConsumerSecret, TokenSecret);

            // create authorization header
            var authHeader = "OAuth ";

            authHeader += string.Format("{0}=\"{1}\"", "oauth_signature", signature);

            foreach (var item in oauthArguments)
            {
                authHeader += string.Format(", {0}=\"{1}\"", item.Key, item.Value);
            }
            request.AddHeader("Authorization", authHeader);
        }
        void AddOAuthData(IRestClient client, IRestRequest request, OAuthWorkflow workflow)
        {
            var requestUrl = client.BuildUriWithoutQueryParameters(request);

            if (requestUrl.Contains('?'))
            {
                throw new ApplicationException(
                          "Using query parameters in the base URL is not supported for OAuth calls. Consider using AddDefaultQueryParameter instead."
                          );
            }

            var url = client.BuildUri(request).ToString();
            var queryStringStart = url.IndexOf('?');

            if (queryStringStart != -1)
            {
                url = url.Substring(0, queryStringStart);
            }

            var method = request.Method.ToString().ToUpperInvariant();

            var parameters = new WebPairCollection();

            // 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 separate class for each OAuth version
            bool BaseQuery(Parameter x)
            => x.Type == ParameterType.GetOrPost || x.Type == ParameterType.QueryString || x.Type == ParameterType.QueryStringWithoutEncode;

            var query =
                request.AlwaysMultipartFormData || request.Files.Count > 0
                    ? x => BaseQuery(x) && x.Name.StartsWith("oauth_")
                    : (Func <Parameter, bool>)BaseQuery;

            parameters.AddRange(client.DefaultParameters.Where(query).ToWebParameters());
            parameters.AddRange(request.Parameters.Where(query).ToWebParameters());

            if (Type == OAuthType.RequestToken)
            {
                workflow.RequestTokenUrl = url;
            }
            else
            {
                workflow.AccessTokenUrl = url;
            }

            var oauth = Type switch
            {
                OAuthType.RequestToken => workflow.BuildRequestTokenInfo(method, parameters),
                OAuthType.AccessToken => workflow.BuildAccessTokenSignature(method, parameters),
                OAuthType.ClientAuthentication => workflow.BuildClientAuthAccessTokenSignature(method, parameters),
                OAuthType.ProtectedResource => workflow.BuildProtectedResourceSignature(method, parameters, url),
                _ => throw new ArgumentOutOfRangeException()
            };

            parameters.Add("oauth_signature", oauth);

            var oauthParameters = ParameterHandling switch
            {
                OAuthParameterHandling.HttpAuthorizationHeader => CreateHeaderParameters(),
                OAuthParameterHandling.UrlOrPostParameters => CreateUrlParameters(),
                _ =>
                throw new ArgumentOutOfRangeException()
            };

            request.AddOrUpdateParameters(oauthParameters);

            IEnumerable <Parameter> CreateHeaderParameters()
            => new[] { new Parameter("Authorization", GetAuthorizationHeader(parameters), ParameterType.HttpHeader) };

            IEnumerable <Parameter> CreateUrlParameters()
            => parameters.Where(p => !p.Name.IsNullOrBlank() && (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_")))
            .Select(p => new Parameter(p.Name, HttpUtility.UrlDecode(p.Value), ParameterType.GetOrPost));
        }

        string GetAuthorizationHeader(WebPairCollection parameters)
        {
            var oathParameters =
                parameters
                .OrderBy(x => x, WebPair.Comparer)
                .Where(
                    p =>
                    !p.Name.IsNullOrBlank() && !p.Value.IsNullOrBlank() &&
                    (p.Name.StartsWith("oauth_") || p.Name.StartsWith("x_auth_"))
                    )
                .Select(x => $"{x.Name}=\"{x.Value}\"")
                .ToList();

            if (!Realm.IsNullOrBlank())
            {
                oathParameters.Insert(0, $"realm=\"{OAuthTools.UrlEncodeRelaxed(Realm)}\"");
            }

            return("OAuth " + string.Join(",", oathParameters));
        }
    }