示例#1
0
        /// <summary>
        /// Gets the access token from the remote server.
        /// </summary>
        protected override void GetAccessToken()
        {
            // authorization code is required for request
            if (String.IsNullOrEmpty(this.AuthorizationCode))
            {
                throw new ArgumentNullException("AuthorizationCode");
            }

            // set default access tken value
            this.AccessToken = Nemiro.OAuth.AccessToken.Empty;

            // prepare
            this.Authorization.PrepareForAccessToken();

            // set request data
            this.Authorization.Verifier    = this.AuthorizationCode;
            this.Authorization.Token       = this.RequestToken.OAuthToken;
            this.Authorization.TokenSecret = this.RequestToken.OAuthTokenSecret;

            // send request
            base.AccessToken = new OAuthAccessToken
                               (
                OAuthUtility.Post
                (
                    this.AccessTokenUrl,
                    authorization: this.Authorization,
                    headers: new NameValueCollection {
                { "Accept", "text/plain" }
            }                                                             // application/x-www-form-urlencoded ???
                )
                               );

            // remove oauth_verifier from headers
            this.Authorization.Remove("oauth_verifier");
        }
示例#2
0
        /// <summary>
        /// Returns a string containing a number.
        /// </summary>
        /// <param name="value">The value for processing.</param>
        internal static object GetNumber(object value)
        {
            if (OAuthUtility.IsEmpty(value))
            {
                return(0);
            }
            if (value.GetType() == typeof(UniValue) || value.GetType().IsSubclassOf(typeof(UniValue)))
            {
                if (((UniValue)value).IsBoolean)
                {
                    return(Convert.ToBoolean(value));
                }
            }
            string str = value.ToString();

            if (Regex.IsMatch(value.ToString(), @",|\."))
            {
                return(Convert.ToDecimal(Regex.Replace(Regex.Replace(str, @",|\.", NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator), @"\s+", "")));
            }
            else
            {
                int int32;
                if (Int32.TryParse(str, out int32))
                {
                    return(int32);
                }
                long int64;
                if (Int64.TryParse(str, out int64))
                {
                    return(int64);
                }
                return(Regex.Replace(str, @"\s+", ""));
            }
        }
示例#3
0
        /// <summary>
        /// Gets the request token from the remote server.
        /// </summary>
        public virtual void GetRequestToken()
        {
            this.Authorization.PrepareForRequestToken();

            if (!String.IsNullOrEmpty(this.ReturnUrl))
            {
                this.Authorization.Callback = String.Format
                                              (
                    "{0}{1}state={2}",
                    this.ReturnUrl,
                    (this.ReturnUrl.Contains("?") ? "&" : "?"),
                    this.State
                                              );
            }

            _RequestToken = new OAuthRequestToken
                            (
                OAuthUtility.Post
                (
                    this.RequestTokenUrl,
                    authorization: this.Authorization,
                    headers: new NameValueCollection {
                { "Accept", "text/plain" }
            }                                                             // application/x-www-form-urlencoded ???
                ),
                this.AuthorizeUrl,
                this.Parameters
                            );
        }
示例#4
0
 /// <summary>
 /// Adds the specified key and value to the collection.
 /// </summary>
 /// <param name="key">The key of the element to add.</param>
 /// <param name="value">The value of the element to add.</param>
 public void Add(string key, UniValue value)
 {
     if (String.IsNullOrEmpty(key))
     {
         key = "____";
     }
     if (!this.ContainsKey(key))
     {
         // first key
         value.Key    = key;
         value.Parent = this.Parent;
         this.Items.Add(key, value);
         if (this.Parent != null && this.Parent.IsArraySubtype && !OAuthUtility.IsNumeric(key))
         {
             this.Parent.IsArraySubtype = false;
         }
     }
     else
     {
         // key exists
         if (this[key].IsArraySubtype)
         {
             // is array, push item
             this[key].Add(this[key].Count.ToString(), value);
         }
         else
         {
             // is not array, create it
             this[key]        = new UniValue(new UniValue[] { new UniValue(this[key]), value });
             this[key].Parent = this.Parent;
         }
         this[key].Key = key;
     }
 }
示例#5
0
 /// <summary>
 /// Returns an encoded string of the value.
 /// </summary>
 public string ToEncodedString(UrlEncodingType encodingType)
 {
     if (this.Value == null)
     {
         return(null);
     }
     return(OAuthUtility.UrlEncode(this.ToString(), encodingType));
 }
示例#6
0
 internal static bool IsNumeric(object value)
 {
     if (OAuthUtility.IsEmpty(value))
     {
         return(false);
     }
     if (value.GetType() == typeof(UniValue) || value.GetType().IsSubclassOf(typeof(UniValue)))
     {
         return(((UniValue)value).IsNumeric);
     }
     return(Regex.IsMatch(value.ToString(), "^[0-9]+$", RegexOptions.Singleline));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OAuthRequestToken"/> class.
 /// </summary>
 /// <param name="result">The request result.</param>
 /// <param name="authorizeUrl">The address of the authorization.</param>
 /// <param name="parameters">The query parameters. Will be used in the formation of the authorization address.</param>
 public OAuthRequestToken(RequestResult result, string authorizeUrl, NameValueCollection parameters) : base(result)
 {
     _OAuthToken             = base["oauth_token"].ToString();
     _OAuthTokenSecret       = base["oauth_token_secret"].ToString();
     _OAuthCallbackConfirmed = Convert.ToBoolean(base["oauth_callback_confirmed"]);
     _AuthorizationUrl       = authorizeUrl;
     _AuthorizationUrl      += _AuthorizationUrl.EndsWith("?") ? "&" : "?";
     _AuthorizationUrl      += String.Format("oauth_token={0}", OAuthUtility.UrlEncode(_OAuthToken));
     if (parameters != null && parameters.Count > 0)
     {
         _AuthorizationUrl += "&" + parameters.ToParametersString("&");
     }
 }
 /// <summary>
 /// Gets signature for the current request.
 /// </summary>
 /// <param name="httpMethod">The HTTP method: <b>GET</b> or <b>POST</b>. Default is <b>POST</b>.</param>
 /// <param name="url">The request URI.</param>
 /// <param name="tokenSecret">The token secret.</param>
 /// <param name="parameters">The query parameters.</param>
 /// <param name="applicationSecret">The application secret key obtained from the provider website.</param>
 /// <param name="authorization">The authorization parameters.</param>
 public static OAuthSignature GetSignature(string httpMethod, Uri url, string applicationSecret, string tokenSecret, NameValueCollection parameters, OAuthAuthorization authorization)
 {
     if (authorization == null)
     {
         throw new ArgumentNullException("authorization");
     }
     return(new OAuthSignature
            (
                authorization["oauth_signature_method"].ToString(),
                String.Format("{0}&{1}", applicationSecret, tokenSecret),
                OAuthUtility.GetSignatureBaseString(httpMethod, url, parameters, authorization)
            ));
 }
        /// <summary>
        /// Returns OAuth string of the current object for Authorization header.
        /// </summary>
        public override string ToString()
        {
            StringBuilder result = new StringBuilder();

            foreach (var itm in this.ParametersSorted)
            {
                if (result.Length > 0)
                {
                    result.Append(", ");
                }
                result.AppendFormat("{0}=\"{1}\"", itm.Key, OAuthUtility.UrlEncode(itm.Value.ToString()));
            }
            result.Insert(0, "OAuth ");
            return(result.ToString());
        }
示例#10
0
        /// <summary>
        /// Creates a shallow copy of the current object.
        /// </summary>
        /// <returns>A shallow copy of the current object.</returns>
        /// <remarks>
        /// <para>Method creates a copy of the current object, removes tokens, change the return address, query parameters and state.</para>
        /// <para>Unfortunately, I made a mistake in architecture, so I had to make this method.</para>
        /// </remarks>
        /// <seealso cref="Clone(NameValueCollection, string)"/>
        public object Clone()
        {
            OAuthBase result = this.MemberwiseClone() as OAuthBase;

            result.State             = OAuthUtility.GetRandomKey();
            result.AccessToken       = null;
            result.AuthorizationCode = null;

            if (result.GetType().IsSubclassOf(typeof(OAuthClient)))
            {
                ((OAuthClient)result).RequestToken = null;
            }

            OAuthManager.AddRequet(result.State, result);

            return(result);
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthClient"/> class.
        /// </summary>
        /// <param name="requestTokenUrl">The address for the request token.</param>
        /// <param name="authorizeUrl">The address for login.</param>
        /// <param name="accessTokenUrl">The address for the access token.</param>
        /// <param name="consumerKey">The application identifier.</param>
        /// <param name="consumerSecret">The application secret key.</param>
        /// <param name="signatureMethod">The name of hashing algorithm to calculate the signature: HMAC-SHA1 (default) or PLAINTEXT.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="requestTokenUrl"/> is null or empty.</exception>
        public OAuthClient(string requestTokenUrl, string authorizeUrl, string accessTokenUrl, string consumerKey, string consumerSecret, string signatureMethod = SignatureMethods.HMACSHA1) : base(authorizeUrl, accessTokenUrl, consumerKey, consumerSecret)
        {
            if (String.IsNullOrEmpty(requestTokenUrl))
            {
                throw new ArgumentNullException("requestTokenUrl");
            }

            this.RequestTokenUrl = requestTokenUrl;

            this.Authorization["oauth_consumer_key"]     = consumerKey;
            this.Authorization["oauth_nonce"]            = OAuthUtility.GetRandomKey();
            this.Authorization["oauth_signature"]        = "";
            this.Authorization["oauth_signature_method"] = signatureMethod;
            this.Authorization["oauth_timestamp"]        = OAuthUtility.GetTimeStamp();
            this.Authorization["oauth_token"]            = "";
            this.Authorization["oauth_version"]          = "1.0";
        }
示例#12
0
        /// <summary>
        /// Creates a shallow copy of the current object.
        /// </summary>
        /// <returns>A shallow copy of the current object.</returns>
        /// <remarks>
        /// <para>Method creates a copy of the current object, removes tokens, change the return address, query parameters and state.</para>
        /// <para>Unfortunately, I made a mistake in architecture, so I had to make this method.</para>
        /// </remarks>
        /// <seealso cref="Clone(NameValueCollection, string)"/>
        public object Clone()
        {
            OAuthBase result = this.MemberwiseClone() as OAuthBase;

            result.State             = OAuthUtility.GetRandomKey();
            result.AccessToken       = null;
            result.AuthorizationCode = null;

            if (result.GetType().IsSubclassOf(typeof(OAuthClient)))
            {
                ((OAuthClient)result).RequestToken = null;
            }

            // I do not remember, why. I'll try to change it. // v1.8
            // OAuthManager.AddRequest(result.State, result.ProviderName, result);
            // --

            return(result);
        }
示例#13
0
 /// <summary>
 /// Encodes a <b>URL</b> string using the specified encoding object.
 /// </summary>
 /// <param name="value">The text to encode.</param>
 /// <param name="codePage">The <see cref="System.Text.Encoding"/> object that specifies the encoding scheme. </param>
 /// <param name="encodingType">The type of the encoder.</param>
 public static string UrlEncode(string value, UrlEncodingType encodingType, Encoding codePage)
 {
     if (String.IsNullOrEmpty(value))
     {
         return(String.Empty);
     }
     if (encodingType == UrlEncodingType.PercentEncoding)
     {
         return(OAuthUtility.PercentEncode(value, codePage));
     }
     else if (encodingType == UrlEncodingType.Default)
     {
         return(HttpUtility.UrlEncode(value, codePage));
     }
     else
     {
         return(value);
     }
 }
示例#14
0
 /// <summary>
 /// Returns an encoded string of the value.
 /// </summary>
 public string ToEncodedString(UrlEncodingType encodingType)
 {
     if (this.Value == null)
     {
         return(null);
     }
     if (encodingType == UrlEncodingType.Default)
     {
         return(HttpUtility.UrlEncode(this.ToString()));
     }
     else if (encodingType == UrlEncodingType.PercentEncoding)
     {
         return(OAuthUtility.UrlEncode(this.ToString()));
     }
     else
     {
         return(this.ToString());
     }
 }
示例#15
0
 /// <summary>
 /// Returns a string that represents the specified <see cref="UniValue"/> instance.
 /// </summary>
 /// <param name="value">The value to converted.</param>
 private string ValueToString(UniValue value)
 {
     if (value.IsString)
     {
         return(String.Format("\"{0}\"", OAuthUtility.JavaScriptStringEncode(value.ToString())));
     }
     else if (value.IsBoolean)
     {
         return(String.Format("{0}", value.ToString().ToLower()));
     }
     else if (value.IsDateTime)
     {
         return(String.Format("\"{0}\"", ((DateTime)value).ToString("r")));
     }
     else if (value.IsNumeric)
     {
         return(String.Format("{0}", value.ToString().Replace(",", ".")));
     }
     else
     {
         return(!value.HasValue ? "null" : value.ToString());
     }
 }
示例#16
0
        /// <summary>
        /// Sends a request to refresh the access token.
        /// </summary>
        /// <param name="accessToken">May contain an access token, which should be refreshed.</param>
        /// <remarks>
        /// <para>If <paramref name="accessToken"/> parameter is not specified, it will use the current access token from the same property of the current class instance.</para>
        /// <para>Token must contain the <b>refresh_token</b>, which was received together with the access token.</para>
        /// </remarks>
        /// <exception cref="NotSupportedException">
        /// <para>Provider does not support refreshing the access token, or the method is not implemented.</para>
        /// <para>Use the property <see cref="OAuthBase.SupportRefreshToken"/>, to check the possibility of calling this method.</para>
        /// </exception>
        /// <exception cref="AccessTokenException">
        /// <para>Access token is not found or is not specified.</para>
        /// <para>-or-</para>
        /// <para><b>refresh_token</b> value is empty.</para>
        /// </exception>
        /// <exception cref="RequestException">Error during execution of a web request.</exception>
        public override AccessToken RefreshToken(AccessToken accessToken = null)
        {
            if (!this.SupportRefreshToken)
            {
                throw new NotSupportedException();
            }

            var token = (OAuth2AccessToken)base.GetSpecifiedTokenOrCurrent(accessToken, refreshTokenRequired: true);

            //HttpAuthorization authorization = null;
            var parameters = new NameValueCollection
            {
                { "client_id", this.ApplicationId },
                { "client_secret", this.ApplicationSecret },
                { "grant_type", GrantType.RefreshToken },
                { "refresh_token", token.RefreshToken }
            };

            /*if (!String.IsNullOrEmpty(token.TokenType) && token.TokenType.Equals(AccessTokenType.Bearer, StringComparison.OrdinalIgnoreCase))
             * {
             * authorization = new HttpAuthorization(AuthorizationType.Bearer, accessToken.Value);
             * }
             * else
             * {
             * parameters.Add("access_token", accessToken.Value);
             * }*/

            var result = OAuthUtility.Post
                         (
                this.AccessTokenUrl,
                parameters: parameters,
                accessToken: token
                //authorization: authorization
                         );

            return(new OAuth2AccessToken(result));
        }
示例#17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuthBase"/> class.
        /// </summary>
        /// <param name="authorizeUrl">The address for login.</param>
        /// <param name="accessTokenUrl">The address for the access token.</param>
        /// <param name="applicationId">The application identifier obtained from the provider website.</param>
        /// <param name="applicationSecret">The application secret key obtained from the provider website.</param>
        /// <exception cref="ArgumentNullException">
        /// <para><paramref name="authorizeUrl"/> is <b>null</b> or <b>empty</b>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="accessTokenUrl"/> is <b>null</b> or <b>empty</b>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="applicationId"/> is <b>null</b> or <b>empty</b>.</para>
        /// <para>-or-</para>
        /// <para><paramref name="applicationSecret"/> is <b>null</b> or <b>empty</b>.</para>
        /// </exception>
        public OAuthBase(string authorizeUrl, string accessTokenUrl, string applicationId, string applicationSecret)
        {
            if (String.IsNullOrEmpty(authorizeUrl))
            {
                throw new ArgumentNullException("authorizeUrl");
            }
            if (String.IsNullOrEmpty(accessTokenUrl))
            {
                throw new ArgumentNullException("accessTokenUrl");
            }
            if (String.IsNullOrEmpty(applicationId))
            {
                throw new ArgumentNullException("applicationId");
            }
            if (String.IsNullOrEmpty(applicationSecret))
            {
                throw new ArgumentNullException("applicationSecret");
            }

            this.AuthorizeUrl      = authorizeUrl;
            this.AccessTokenUrl    = accessTokenUrl;
            this.ApplicationId     = applicationId;
            this.ApplicationSecret = applicationSecret;

            // set unique identifier to the instance
            this.State = OAuthUtility.GetRandomKey();

            // default values
            this.SupportRefreshToken = false;
            this.SupportRevokeToken  = false;

            // I do not remember, why. I'll try to change it. // v1.8
            // add the instance to the clients collection
            // OAuthManager.AddRequest(this.State, this.ProviderName, this);
            // --
        }
示例#18
0
        /// <summary>
        /// Performs an async request.
        /// </summary>
        /// <param name="method">HTTP Method: <b>POST</b> (default), <b>PUT</b>, <b>GET</b> or <b>DELETE</b>.</param>
        /// <param name="endpoint">URL to which will be sent to request.</param>
        /// <param name="parameters">Parameters to be passed to request.</param>
        /// <param name="authorization">Authorization header value.</param>
        /// <param name="headers">HTTP headers for request.</param>
        /// <param name="contentType">The value of the <b>Content-Type</b> HTTP header.</param>
        /// <param name="callback">A delegate that, if provided, is called when an async web request is completed.</param>
        /// <param name="accessToken">Access token to be used in the request.</param>
        /// <remarks>
        /// <para>Can not be used simultaneously <paramref name="accessToken"/> and <paramref name="authorization"/>. Use only one of these parameters.</para>
        /// </remarks>
        /// <returns>Returns an instance of the <see cref="RequestResult"/> class, which contains the result of the request.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="RequestException"></exception>
        /// <exception cref="ArgumentException">
        /// <para>The exception occurs when the query parameters are specified at the same time <paramref name="authorization"/> and <paramref name="accessToken"/>.</para>
        /// </exception>
        public static void ExecuteRequestAsync(string method = "POST", string endpoint = null, HttpParameterCollection parameters = null, HttpAuthorization authorization = null, NameValueCollection headers = null, string contentType = null, AccessToken accessToken = null, ExecuteRequestAsyncCallback callback = null)
        {
            var t = new Thread
                        (() =>
            {
                RequestResult result = null;
                try
                {
                    result = OAuthUtility.ExecuteRequest(method, endpoint, parameters, authorization, headers, contentType, accessToken);
                }
                catch (RequestException ex)
                {
                    result = ex.RequestResult;
                }
                if (callback != null)
                {
                    callback(result);
                }
            }
                        );

            t.IsBackground = true;
            t.Start();
        }
示例#19
0
        // [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]

        /// <summary>
        /// Gets the access token from the remote server.
        /// </summary>
        protected override void GetAccessToken()
        {
            // authorization code is required for request
            if (this.GrantType.IsAuthorizationCode && String.IsNullOrEmpty(this.AuthorizationCode))
            {
                throw new ArgumentNullException("AuthorizationCode");
            }
            else if (this.GrantType.IsPassword || this.GrantType.IsClientCredentials)
            {
                if (String.IsNullOrEmpty(this.Username))
                {
                    throw new ArgumentNullException("username");
                }
                if (String.IsNullOrEmpty(this.Password))
                {
                    throw new ArgumentNullException("password");
                }
            }

            // set default access token value
            this.AccessToken = Nemiro.OAuth.AccessToken.Empty;

            // set request data
            HttpAuthorization   auth       = null;
            NameValueCollection parameters = new NameValueCollection();

            if (this.GrantType.IsAuthorizationCode)
            {
                // http://tools.ietf.org/html/rfc6749#section-4.1.3
                parameters.Add("code", this.AuthorizationCode);
            }
            else if (this.GrantType.IsPassword)
            {
                // http://tools.ietf.org/html/rfc6749#section-4.3.2
                parameters.Add("username", this.Username);
                parameters.Add("password", this.Password);
            }
            else if (this.GrantType.IsClientCredentials)
            {
                // http://tools.ietf.org/html/rfc6749#section-4.4.2
                auth = new HttpAuthorization(AuthorizationType.Basic, OAuthUtility.ToBase64String("{0}:{1}", this.Username, this.Password));
            }
            else
            {
                throw new NotSupportedException(String.Format("GrantType '{0}' is not supported. Please write the code ;)", this.GrantType));
            }

            parameters.Add("client_id", this.ApplicationId);
            parameters.Add("client_secret", this.ApplicationSecret);
            parameters.Add("grant_type", this.GrantType);


            if (!String.IsNullOrEmpty(this.ReturnUrl))
            {
                parameters.Add("redirect_uri", this.ReturnUrl);
            }

            var result = OAuthUtility.Post
                         (
                this.AccessTokenUrl,
                parameters,
                auth
                         );

            if (result.ContainsKey("error"))
            {
                this.AccessToken = new AccessToken(new ErrorResult(result));
            }
            else
            {
                this.AccessToken = new OAuth2AccessToken(result);
            }
        }
示例#20
0
        /// <summary>
        /// Performs a web request.
        /// </summary>
        /// <param name="method">HTTP Method: <b>POST</b> (default) or <b>GET</b>.</param>
        /// <param name="endpoint">URL to which will be sent to web request.</param>
        /// <param name="parameters">Parameters to be passed to web request.</param>
        /// <param name="authorization">Authorization header value.</param>
        /// <param name="headers">HTTP headers for web request.</param>
        /// <returns>Returns an instance of the <see cref="RequestResult"/> class, which contains the result of the web request.</returns>
        /// <exception cref="System.ArgumentNullException"></exception>
        /// <exception cref="RequestException"></exception>
        public static RequestResult ExecuteRequest(string method = "POST", string endpoint = null, NameValueCollection parameters = null, string authorization = null, NameValueCollection headers = null)
        {
            if (String.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("endpoint");
            }
            if (String.IsNullOrEmpty(method))
            {
                method = "POST";
            }

            // set protocols
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
            // ignore errors
            ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
            // --

            // set parameters to the URL if the request is executed using the GET method
            if (method.Equals("GET", StringComparison.OrdinalIgnoreCase) && parameters != null && parameters.Count > 0)
            {
                endpoint += (endpoint.Contains("?") ? "&" : "?");
                endpoint += parameters.ToParametersString("&");
            }

            // create request
            var req = (HttpWebRequest)HttpWebRequest.Create(endpoint);

            // http method
            req.Method = method.ToUpper();

            // req.ProtocolVersion = HttpVersion.Version10;

            // user-agent (required for some providers)
            req.UserAgent = "Nemiro.OAuth";

            // json format acceptable for the response
            req.Accept = "application/json";

            // set parameters to the body if the request is executed using the POST method
            if (method.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                req.ContentType = "application/x-www-form-urlencoded";
                if (parameters != null && parameters.Count > 0)
                {
                    byte[] b = System.Text.Encoding.ASCII.GetBytes(parameters.ToParametersString("&"));
                    // for .NET Framework 2.0/3.0/3.5
                    if (Environment.Version.Major < 4)
                    {
                        req.ContentLength = b.Length;
                    }
                    // --
                    req.GetRequestStream().Write(b, 0, b.Length);
                }
                else
                {
                    // for some servers
                    req.ContentLength = 0;
                }
            }

            // set authorization header
            if (!String.IsNullOrEmpty(authorization))
            {
                if (headers == null)
                {
                    headers = new NameValueCollection();
                }
                if (String.IsNullOrEmpty(headers["Authorization"]))
                {
                    headers.Add("Authorization", authorization);
                }
                else
                {
                    headers["Authorization"] = authorization;
                }
            }

            // headers
            if (headers != null)
            {
                req.Headers.Add(headers);
            }

            Exception exception = null;
            string    result = "", contentType = "";

            try
            {
                // executes the request
                using (var resp = (HttpWebResponse)req.GetResponse())
                {
                    contentType = resp.ContentType;
                    result      = OAuthUtility.ReadResponseStream(resp);
                }
            }
            catch (WebException ex)
            {     // web exception,
                if (ex.Response != null)
                { // reading contents of the response
                    using (var resp = (HttpWebResponse)ex.Response)
                    {
                        contentType = resp.ContentType;
                        result      = OAuthUtility.ReadResponseStream(resp);
                    }
                }
                else
                { // no response, get error message
                    result = ex.Message;
                }
                exception = ex;
            }
            catch (Exception ex)
            { // other exception
                result    = ex.Message;
                exception = ex;
            }

            // exception
            if (exception != null)
            {
                throw new RequestException(contentType, result, exception);
            }

            // result
            return(new RequestResult(contentType, result));
        }
        /// <summary>
        /// Gets base string of the signature for current request (OAuth 1.0).
        /// </summary>
        /// <remarks><para>For more details, please visit <see href="http://tools.ietf.org/html/rfc5849#section-3.4.1.1"/></para></remarks>
        public static string GetSignatureBaseString(string httpMethod, Uri url, NameValueCollection parameters, OAuthAuthorization authorization)
        {
            if (String.IsNullOrEmpty(httpMethod))
            {
                throw new ArgumentNullException("httpMethod");
            }
            if (authorization == null)
            {
                throw new ArgumentNullException("authorization");
            }
            if (url == null)
            {
                throw new ArgumentNullException("url");
            }

            var param = new NameValueCollection();

            if (parameters != null)
            {
                param.Add(parameters);
            }

            // append the authorization headers
            foreach (KeyValuePair <string, UniValue> itm in authorization.Value.CollectionItems)
            {
                if (itm.Key.Equals("oauth_signature", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }
                param.Add(itm.Key, itm.Value.ToString());
            }

            // append the query parameters
            string queryString = url.GetComponents(UriComponents.Query, UriFormat.Unescaped);

            if (!String.IsNullOrEmpty(queryString))
            {
                foreach (string q in queryString.Split('&'))
                {
                    string[] p = q.Split('=');
                    string   key = p.First(), value = (p.Length > 1 ? p.Last() : "");
                    param.Add(key, value);
                }
            }

            // sorting and build base string of the signature
            StringBuilder signBaseString = new StringBuilder();

            foreach (var itm in param.Sort().ToKeyValuePairCollection())
            {
                //if (itm.Key.Equals("oauth_verifier", StringComparison.OrdinalIgnoreCase)) { continue; }
                if (signBaseString.Length > 0)
                {
                    signBaseString.Append(OAuthUtility.UrlEncode("&"));
                }
                signBaseString.Append(OAuthUtility.UrlEncode(String.Format("{0}={1}", itm.Key, OAuthUtility.UrlEncode(itm.Value))));
            }

            signBaseString.Insert(0, String.Format("{0}&{1}&", httpMethod.ToUpper(), OAuthUtility.UrlEncode(url.ToString())));

            return(signBaseString.ToString());
        }
 /// <summary>
 /// Sets signature.
 /// </summary>
 /// <param name="httpMethod">The HTTP method: <b>GET</b> or <b>POST</b>. Default is <b>POST</b>.</param>
 /// <param name="url">The request URI.</param>
 /// <param name="tokenSecret">The token secret.</param>
 /// <param name="parameters">The query parameters.</param>
 /// <param name="applicationSecret">The application secret key obtained from the provider website.</param>
 public void SetSignature(string httpMethod, Uri url, string applicationSecret, string tokenSecret, NameValueCollection parameters)
 {
     this["oauth_signature"] = OAuthUtility.GetSignature(httpMethod, url, applicationSecret, tokenSecret, parameters, this);
 }
示例#23
0
 /// <summary>
 /// Updates the nonce and timestamp.
 /// </summary>
 private void UpdateStamp()
 {
     this.Authorization["oauth_nonce"]     = OAuthUtility.GetRandomKey();
     this.Authorization["oauth_timestamp"] = OAuthUtility.GetTimeStamp();
 }
示例#24
0
 /// <summary>
 /// Gets base string of the signature for current request (OAuth 1.0).
 /// </summary>
 /// <remarks><para>For more details, please visit <see href="http://tools.ietf.org/html/rfc5849#section-3.4.1.1"/></para></remarks>
 public static string GetSignatureBaseString(string httpMethod, string url, NameValueCollection parameters, OAuthAuthorization authorization)
 {
     return(OAuthUtility.GetSignatureBaseString(httpMethod, new Uri(url), parameters, authorization));
 }
 /// <summary>
 /// Updates the nonce and the timestamp.
 /// </summary>
 internal void UpdateStamp()
 {
     this.Nonce     = OAuthUtility.GetRandomKey();
     this.Timestamp = OAuthUtility.GetTimeStamp();
 }
示例#26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientName"/>.
 /// </summary>
 /// <param name="key">The client name. Any string.</param>
 /// <param name="providerName">The provider name.</param>
 internal ClientName(string key, string providerName)
 {
     _Key          = key;
     _ProviderName = providerName;
     _Hash         = OAuthUtility.GetMD5Hash(String.Format("{0}/{1}", key, providerName).ToLower());
 }
 public void SetSignature(string httpMethod, Uri url, NameValueCollection parameters)
 {
     this["oauth_signature"] = OAuthUtility.GetSignature(httpMethod, url, this.ConsumerSecret, this.TokenSecret, parameters, this).ToString();
 }
示例#28
0
 private string GetSignatureBaseString(string httpMethod, Uri url, NameValueCollection parameters)
 {
     return(OAuthUtility.GetSignatureBaseString(httpMethod, url, parameters, this.Authorization));
 }
示例#29
0
 public OAuthSignature GetSignature(string httpMethod, Uri url, string tokenSecret, NameValueCollection parameters)
 {
     return(OAuthUtility.GetSignature(httpMethod, url, this.ApplicationSecret, tokenSecret, parameters, this.Authorization));
 }
示例#30
0
 /// <summary>
 /// Gets signature for the current request.
 /// </summary>
 /// <param name="httpMethod">The HTTP method: <b>GET</b> or <b>POST</b>. Default is <b>POST</b>.</param>
 /// <param name="url">The request URI.</param>
 /// <param name="tokenSecret">The token secret.</param>
 /// <param name="parameters">The query parameters.</param>
 /// <param name="applicationSecret">The application secret key obtained from the provider website.</param>
 /// <param name="authorization">The authorization parameters.</param>
 public static OAuthSignature GetSignature(string httpMethod, string url, string applicationSecret, string tokenSecret, NameValueCollection parameters, OAuthAuthorization authorization)
 {
     return(OAuthUtility.GetSignature(httpMethod, new Uri(url), applicationSecret, tokenSecret, parameters, authorization));
 }