Esempio n. 1
0
        public virtual OAuthWebQueryInfo BuildClientAuthAccessTokenInfo(string method, WebParameterCollection parameters)
        {
            ValidateClientAuthAccessRequestState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }
            Uri    uri       = new Uri(AccessTokenUrl);
            string timestamp = OAuthTools.GetTimestamp();
            string nonce     = OAuthTools.GetNonce();

            AddXAuthParameters(parameters, timestamp, nonce);
            string            signatureBase     = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters);
            string            signature         = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret);
            OAuthWebQueryInfo oAuthWebQueryInfo = new OAuthWebQueryInfo();

            oAuthWebQueryInfo.WebMethod          = method;
            oAuthWebQueryInfo.ParameterHandling  = ParameterHandling;
            oAuthWebQueryInfo.ClientMode         = "client_auth";
            oAuthWebQueryInfo.ClientUsername     = ClientUsername;
            oAuthWebQueryInfo.ClientPassword     = ClientPassword;
            oAuthWebQueryInfo.ConsumerKey        = ConsumerKey;
            oAuthWebQueryInfo.SignatureMethod    = SignatureMethod.ToRequestValue();
            oAuthWebQueryInfo.SignatureTreatment = SignatureTreatment;
            oAuthWebQueryInfo.Signature          = signature;
            oAuthWebQueryInfo.Timestamp          = timestamp;
            oAuthWebQueryInfo.Nonce          = nonce;
            oAuthWebQueryInfo.Version        = (Version ?? "1.0");
            oAuthWebQueryInfo.TokenSecret    = TokenSecret;
            oAuthWebQueryInfo.ConsumerSecret = ConsumerSecret;
            return(oAuthWebQueryInfo);
        }
Esempio n. 2
0
        public virtual OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParameterCollection parameters)
        {
            ValidateTokenRequestState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }
            string timestamp = OAuthTools.GetTimestamp();
            string nonce     = OAuthTools.GetNonce();

            AddAuthParameters(parameters, timestamp, nonce);
            string            signatureBase     = OAuthTools.ConcatenateRequestElements(method, RequestTokenUrl, parameters);
            string            signature         = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret);
            OAuthWebQueryInfo oAuthWebQueryInfo = new OAuthWebQueryInfo();

            oAuthWebQueryInfo.WebMethod          = method;
            oAuthWebQueryInfo.ParameterHandling  = ParameterHandling;
            oAuthWebQueryInfo.ConsumerKey        = ConsumerKey;
            oAuthWebQueryInfo.SignatureMethod    = SignatureMethod.ToRequestValue();
            oAuthWebQueryInfo.SignatureTreatment = SignatureTreatment;
            oAuthWebQueryInfo.Signature          = signature;
            oAuthWebQueryInfo.Timestamp          = timestamp;
            oAuthWebQueryInfo.Nonce          = nonce;
            oAuthWebQueryInfo.Version        = (Version ?? "1.0");
            oAuthWebQueryInfo.Callback       = OAuthTools.UrlEncodeRelaxed(CallbackUrl ?? "");
            oAuthWebQueryInfo.TokenSecret    = TokenSecret;
            oAuthWebQueryInfo.ConsumerSecret = ConsumerSecret;
            return(oAuthWebQueryInfo);
        }
Esempio n. 3
0
        public static OpenAuthAccessToken GetAccessToken(Uri uri, string consumerKey, string consumerSecret, string token, string tokenSecret, string verifier, SignatureMethod signatureMethod = SignatureMethod.HMACSHA1)
        {
            var timestamp = GenerateTimeStamp();
            var nonce = GenerateNonce(timestamp);

            var parameters = ExtractQueryString(uri.Query);
            parameters.Add(new Parameter(OAuthParameter.ConsumerKey.Value(), consumerKey));
            parameters.Add(new Parameter(OAuthParameter.SignatureMethod.Value(), signatureMethod.Value()));
            parameters.Add(new Parameter(OAuthParameter.Timestamp.Value(), timestamp));
            parameters.Add(new Parameter(OAuthParameter.Nonce.Value(), nonce));
            parameters.Add(new Parameter(OAuthParameter.Version.Value(), OAuthVersion));
            parameters.Add(new Parameter(OAuthParameter.Token.Value(), token));
            parameters.Add(new Parameter(OAuthParameter.Verifier.Value(), verifier));

            string signatureBaseString = GenerateSignatureBaseString(HttpMethod.Post, uri, parameters);
            string signature = GenerateSignature(consumerSecret, signatureMethod, signatureBaseString, tokenSecret);
            string header = GenerateHeader(consumerKey, signatureMethod.Value(), signature, timestamp, nonce, OAuthVersion, null, token, verifier);

            string response = Utils.Request(HttpMethod.Post, uri, header);
            NameValueCollection data = HttpUtility.ParseQueryString(response);
            if (!data.AllKeys.Contains(OAuthParameter.Token.Value()) || !data.AllKeys.Contains(OAuthParameter.TokenSecret.Value()))
                throw new OpenAuthException { Error = OpenAuthErrorType.MissingKeys };

            return new OpenAuthAccessToken {
                Token = data[OAuthParameter.Token.Value()],
                TokenSecret = data[OAuthParameter.TokenSecret.Value()]
            };
        }
Esempio n. 4
0
        WebPairCollection GenerateAuthParameters(string timestamp, string nonce)
        {
            var authParameters = new WebPairCollection
            {
                new WebPair("oauth_consumer_key", ConsumerKey),
                new WebPair("oauth_nonce", nonce),
                new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()),
                new WebPair("oauth_timestamp", timestamp),
                new WebPair("oauth_version", Version ?? "1.0")
            };

            if (!Token.IsEmpty())
            {
                authParameters.Add(new WebPair("oauth_token", Token));
            }

            if (!CallbackUrl.IsEmpty())
            {
                authParameters.Add(new WebPair("oauth_callback", CallbackUrl));
            }

            if (!Verifier.IsEmpty())
            {
                authParameters.Add(new WebPair("oauth_verifier", Verifier));
            }

            if (!SessionHandle.IsEmpty())
            {
                authParameters.Add(new WebPair("oauth_session_handle", SessionHandle));
            }

            return(authParameters);
        }
Esempio n. 5
0
        /// <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>
        /// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
        /// <param name="parameters">Any existing, non-OAuth query parameters desired in the request</param>
        public virtual OAuthWebQueryInfo BuildAccessTokenInfo(string method, WebParameterCollection parameters)
        {
            ValidateAccessRequestState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }
            var uri       = new Uri(AccessTokenUrl);
            var timestamp = OAuthTools.GetTimestamp();
            var nonce     = OAuthTools.GetNonce();

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

            return(info);
        }
Esempio n. 6
0
        /// <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>
        /// <seealso cref="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 virtual OAuthWebQueryInfo BuildClientAuthAccessTokenInfo(string method, WebParameterCollection parameters)
        {
            ValidateClientAuthAccessRequestState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }
            var uri       = new Uri(AccessTokenUrl);
            var timestamp = OAuthTools.GetTimestamp();
            var nonce     = OAuthTools.GetNonce();

            AddXAuthParameters(parameters, timestamp, nonce);
            var signatureBase = OAuthTools.ConcatenateRequestElements(method, uri.ToString(), parameters);
            var signature     = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret);
            var info          = new OAuthWebQueryInfo
            {
                WebMethod          = method,
                ParameterHandling  = ParameterHandling,
                ClientMode         = "client_auth",
                ClientUsername     = ClientUsername,
                ClientPassword     = ClientPassword,
                ConsumerKey        = ConsumerKey,
                SignatureMethod    = SignatureMethod.ToRequestValue(),
                SignatureTreatment = SignatureTreatment,
                Signature          = signature,
                Timestamp          = timestamp,
                Nonce          = nonce,
                Version        = Version ?? "1.0",
                TokenSecret    = TokenSecret,
                ConsumerSecret = ConsumerSecret
            };

            return(info);
        }
Esempio n. 7
0
        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", SignatureMethod.ToRequestValue()),
                new WebPair("oauth_timestamp", timestamp),
                new WebPair("oauth_version", Version ?? "1.0")
            };

            if (!Token.IsNullOrBlank())
            {
                authParameters.Add(new WebPair("oauth_token", Token));
            }
            if (!CallbackUrl.IsNullOrBlank())
            {
                authParameters.Add(new WebPair("oauth_callback", CallbackUrl));
            }
            if (!Verifier.IsNullOrBlank())
            {
                authParameters.Add(new WebPair("oauth_verifier", Verifier));
            }
            if (!SessionHandle.IsNullOrBlank())
            {
                authParameters.Add(new WebPair("oauth_session_handle", SessionHandle));
            }
            foreach (var authParameter in authParameters)
            {
                parameters.Add(authParameter);
            }
        }
Esempio n. 8
0
        private void AddAuthParameters(ICollection <WebPair> parameters, string timestamp, string nonce)
        {
            WebParameterCollection webParameterCollection = new WebParameterCollection();

            webParameterCollection.Add(new WebPair("oauth_consumer_key", ConsumerKey));
            webParameterCollection.Add(new WebPair("oauth_nonce", nonce));
            webParameterCollection.Add(new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()));
            webParameterCollection.Add(new WebPair("oauth_timestamp", timestamp));
            webParameterCollection.Add(new WebPair("oauth_version", Version ?? "1.0"));
            WebParameterCollection webParameterCollection2 = webParameterCollection;

            if (!Token.IsNullOrBlank())
            {
                webParameterCollection2.Add(new WebPair("oauth_token", Token));
            }
            if (!CallbackUrl.IsNullOrBlank())
            {
                webParameterCollection2.Add(new WebPair("oauth_callback", CallbackUrl));
            }
            if (!Verifier.IsNullOrBlank())
            {
                webParameterCollection2.Add(new WebPair("oauth_verifier", Verifier));
            }
            if (!SessionHandle.IsNullOrBlank())
            {
                webParameterCollection2.Add(new WebPair("oauth_session_handle", SessionHandle));
            }
            foreach (WebPair item in webParameterCollection2)
            {
                parameters.Add(item);
            }
        }
Esempio n. 9
0
        /// <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>
        /// <seealso cref="http://oauth.net/core/1.0#anchor9"/>
        /// <returns></returns>
        public virtual OAuthWebQueryInfo BuildRequestTokenInfo(string method, WebParameterCollection parameters)
        {
            ValidateTokenRequestState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }
            var timestamp = OAuthTools.GetTimestamp();
            var nonce     = OAuthTools.GetNonce();

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

            return(info);
        }
Esempio n. 10
0
 public OAuthProcess(ClientCredentials clientCredentials, string temporaryCredentialsRequestEndpoint, string resourceOwnerAuthorizationEndpoint, string tokenRequestEndpoint)
 {
     this.SignatureMethod   = SignatureMethod.HMAC_SHA1;
     this.ClientCredentials = clientCredentials;
     this.TemporaryCredentialsRequestEndpoint = temporaryCredentialsRequestEndpoint;
     this.ResourceOwnerAuthorizationEndpoint  = resourceOwnerAuthorizationEndpoint;
     this.TokenRequestEndpoint = tokenRequestEndpoint;
 }
Esempio n. 11
0
 public OAuth1Authenticator(SignatureMethod method, string consumerKey, string consumerSecret, string tokenKey = null, string tokenSecret = null, string verifier = null)
 {
     Method = method;
     ConsumerKey = consumerKey;
     ConsumerSecret = consumerSecret;
     TokenKey = tokenKey;
     TokenSecret = tokenSecret;
     Verifier = verifier;
 }
Esempio n. 12
0
        public virtual 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);

#if !SILVERLIGHT && !WINDOWS_PHONE
            var urlParameters = HttpUtility.ParseQueryString(uri.Query);
#else
            var urlParameters = uri.Query.ParseQueryString();
#endif
#if !SILVERLIGHT && !WINDOWS_PHONE
            foreach (var parameter in urlParameters.AllKeys)
#else
            foreach (var parameter in urlParameters.Keys)
#endif
            {
                switch (method.ToUpperInvariant())
                {
                case "POST":
                    parameters.Add(new HttpPostParameter(parameter, urlParameters[parameter]));
                    break;

                default:
                    parameters.Add(parameter, urlParameters[parameter]);
                    break;
                }
            }
            var timestamp = OAuthTools.GetTimestamp();
            var nonce     = OAuthTools.GetNonce();
            AddAuthParameters(parameters, timestamp, nonce);
            var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters);
            var signature     = OAuthTools.GetSignature(
                SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret
                );
            var info = new OAuthWebQueryInfo
            {
                WebMethod          = method,
                ParameterHandling  = ParameterHandling,
                ConsumerKey        = ConsumerKey,
                Token              = Token,
                SignatureMethod    = SignatureMethod.ToRequestValue(),
                SignatureTreatment = SignatureTreatment,
                Signature          = signature,
                Timestamp          = timestamp,
                Nonce              = nonce,
                Version            = Version ?? "1.0",
                Callback           = CallbackUrl,
                ConsumerSecret     = ConsumerSecret,
                TokenSecret        = TokenSecret
            };
            return(info);
        }
Esempio n. 13
0
        public virtual 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 = System.Web.HttpUtility.ParseQueryString(uri.Query);

            //...unless they were already present at some point, such as being added to the request object
            foreach (var parameter in urlParameters.AllKeys.Where(k => !parameters.Names.Contains(k)))
            {
                switch (method.ToUpperInvariant())
                {
                case "POST":
                    parameters.Add(new HttpPostParameter(parameter, urlParameters[parameter]));
                    break;

                default:
                    parameters.Add(parameter, urlParameters[parameter]);
                    break;
                }
            }

            var timestamp = OAuthTools.GetTimestamp();
            var nonce     = OAuthTools.GetNonce();

            AddAuthParameters(parameters, timestamp, nonce);

            var signatureBase = OAuthTools.ConcatenateRequestElements(method, url, parameters);
            var signature     = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase,
                                                        ConsumerSecret, TokenSecret);

            var info = new OAuthWebQueryInfo
            {
                WebMethod          = method,
                ParameterHandling  = ParameterHandling,
                ConsumerKey        = ConsumerKey,
                Token              = Token,
                SignatureMethod    = SignatureMethod.ToRequestValue(),
                SignatureTreatment = SignatureTreatment,
                Signature          = signature,
                Timestamp          = timestamp,
                Nonce              = nonce,
                Version            = Version ?? "1.0",
                Callback           = CallbackUrl,
                ConsumerSecret     = ConsumerSecret,
                TokenSecret        = TokenSecret
            };

            return(info);
        }
        protected override string ComputeSignatureCore(string key, string data)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(data));

            using (var algorithm = KeyedHashAlgorithm.Create(SignatureMethod.ToUpperInvariant()))
            {
                algorithm.Key = _encoding.GetBytes(key.ToCharArray());
                return(Convert.ToBase64String(algorithm.ComputeHash(_encoding.GetBytes(data.ToCharArray()))));
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 签名方法
        /// https://www.qcloud.com/document/product/240/8329
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private void GetSignature(string url,
                                  SortedDictionary <string, object> requestParams,
                                  RequestMethod requestMethod     = RequestMethod.GET,
                                  SignatureMethod signatureMethod = SignatureMethod.HmacSHA1)
        {
            /*
             * 1. 对参数排序
             * 2. 拼接请求字符串
             * 3. 拼接签名原文字符串
             * 4. 生成签名串
             * 5. 签名串编码(BASE64编码)
             */
            if (_patameters == null)
            {
                _patameters = new SortedDictionary <string, object>();
            }
            string tempStr = "";

            foreach (string key in requestParams.Keys)
            {
                if (key == "Signature")
                {
                    continue;
                }
                if (requestMethod == RequestMethod.POST && requestParams[key].ToString().Substring(0, 1).Equals("@"))
                {
                    continue;
                }
                tempStr += string.Format("{0}={1}&", key.Replace("_", "."), requestParams[key]);
            }

            tempStr = $"?{tempStr.TrimEnd('&')}";

            string retStr = $"{requestMethod.ToString()}{url}{_ServerUri}{tempStr}";


            if (signatureMethod == SignatureMethod.HmacSHA1)
            {
                using (var mac = new HMACSHA1(Encoding.UTF8.GetBytes(_SecretKey)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(retStr));
                    _patameters.Add("Signature", Convert.ToBase64String(hash));
                }
            }

            if (signatureMethod == SignatureMethod.HmacSHA256)
            {
                using (var mac = new HMACSHA256(Encoding.UTF8.GetBytes(_SecretKey)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(retStr));
                    _patameters.Add("Signature", Convert.ToBase64String(hash));
                    _patameters.Add("SignatureMethod", "HmacSHA256");
                }
            }
        }
Esempio n. 16
0
        private static async Task <ClientResponse <MembershipContainerPage> > GetFilteredMembershipPageAsync(
            HttpClient client, string serviceUrl, string consumerKey, string consumerSecret,
            string contentType, SignatureMethod signatureMethod,
            EventHandler <Newtonsoft.Json.Serialization.ErrorEventArgs> deserializationErrorHandler)
        {
            try
            {
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));

                await SecuredClient.SignRequest(client, HttpMethod.Get, serviceUrl, new StringContent(string.Empty), consumerKey,
                                                consumerSecret, signatureMethod);

                var outcomeResponse = new ClientResponse <MembershipContainerPage>();
                try
                {
                    using (var response = await client.GetAsync(serviceUrl).ConfigureAwait(false))
                    {
                        outcomeResponse.StatusCode = response.StatusCode;
                        if (response.StatusCode == HttpStatusCode.OK)
                        {
                            outcomeResponse.Response = await response.DeserializeJsonObjectAsync <MembershipContainerPage>(deserializationErrorHandler)
                                                       .ConfigureAwait(false);
                        }
#if DEBUG
                        outcomeResponse.HttpRequest = await response.RequestMessage.ToFormattedRequestStringAsync()
                                                      .ConfigureAwait(false);

                        outcomeResponse.HttpResponse = await response.ToFormattedResponseStringAsync()
                                                       .ConfigureAwait(false);
#endif
                    }
                }
                catch (HttpRequestException ex)
                {
                    outcomeResponse.Exception  = ex;
                    outcomeResponse.StatusCode = HttpStatusCode.BadRequest;
                }
                catch (Exception ex)
                {
                    outcomeResponse.Exception  = ex;
                    outcomeResponse.StatusCode = HttpStatusCode.InternalServerError;
                }
                return(outcomeResponse);
            }
            catch (Exception ex)
            {
                return(new ClientResponse <MembershipContainerPage>
                {
                    Exception = ex,
                    StatusCode = HttpStatusCode.InternalServerError
                });
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Get a page of membership.
        /// </summary>
        /// <param name="client">The HTTP client to use for this request.</param>
        /// <param name="serviceUrl">The membership service URL. In LTI 1 the parameter will be in the launch as <code>custom_context_membership</code>.</param>
        /// <param name="consumerKey">The OAuth Consumer Key.</param>
        /// <param name="consumerSecret">The OAuth Consumer Secret to use for signing the request.</param>
        /// <param name="limit">Specifies the maximum number of items that should be delivered per page. This parameter is merely a hint. The server is not obligated to honor this limit and may at its own discretion choose a different value for the number of items per page.</param>
        /// <param name="rlid">The ID of a resource link within the context and associated and the Tool Provider. The result set will be filtered so that it includes only those memberships that are permitted to access the resource link. If omitted, the result set will include all memberships for the context.</param>
        /// <param name="role">The role for a membership. The result set will be filtered so that it includes only those memberships that contain this role. The value of the parameter should be the full URI for the role, although the simple name may be used for context-level roles. If omitted, the result set will include all memberships with any role.</param>
        /// <param name="signatureMethod">The signatureMethod. Defaults to <see cref="SignatureMethod.HmacSha1"/></param>
        public static async Task <ClientResponse <MembershipContainerPage> > GetMembershipPageAsync(
            HttpClient client, string serviceUrl, string consumerKey, string consumerSecret,
            int?limit = null, string rlid = null, ContextRole?role = null, SignatureMethod signatureMethod = SignatureMethod.HmacSha1)
        {
            var filteredServiceUrl = GetFilteredServiceUrl(serviceUrl, limit, rlid, role);

            return(await GetFilteredMembershipPageAsync(
                       client, filteredServiceUrl, consumerKey, consumerSecret,
                       LtiConstants.LisMembershipContainerMediaType, signatureMethod)
                   .ConfigureAwait(false));
        }
Esempio n. 18
0
 public static string ToStringValue(this SignatureMethod value)
 {
     if (Enum.IsDefined(typeof(SignatureMethod), value))
     {
         return(OAuthSignatureMethods[value]);
     }
     else
     {
         throw new NotImplementedException();
     }
 }
Esempio n. 19
0
 WebPairCollection GenerateXAuthParameters(string timestamp, string nonce)
 => new WebPairCollection
 {
     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")
 };
Esempio n. 20
0
        /// <summary>
        /// 签名方法
        /// https://www.qcloud.com/document/product/240/8329
        /// </summary>
        /// <param name="endpoint"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static void GetSignature(string url, string ServerUri, string SecretKey,
                                        SortedDictionary <string, object> requestParams,
                                        RequestMethod requestMethod     = RequestMethod.GET,
                                        SignatureMethod signatureMethod = SignatureMethod.HmacSHA1)
        {
            /*
             * 1. 对参数排序
             * 2. 拼接请求字符串
             * 3. 拼接签名原文字符串
             * 4. 生成签名串
             * 5. 签名串编码(BASE64编码)
             */
            if (requestParams == null)
            {
                requestParams = new SortedDictionary <string, object>();
            }
            StringBuilder tempStr = new StringBuilder();

            foreach (string key in requestParams.Keys)
            {
                if (key == "Signature")
                {
                    continue;
                }
                if (requestMethod == RequestMethod.POST && requestParams[key].ToString().Substring(0, 1).Equals("@"))
                {
                    continue;
                }
                tempStr.Append($"{key.Replace("_", ".")}={requestParams[key]}&");
            }

            string retStr = $"{requestMethod.ToString()}{url}{ServerUri}{tempStr.ToString().TrimEnd('&')}";

            if (signatureMethod == SignatureMethod.HmacSHA1)
            {
                using (var mac = new HMACSHA1(Encoding.UTF8.GetBytes(SecretKey)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(retStr));
                    requestParams.Add("Signature", Convert.ToBase64String(hash));
                }
            }

            if (signatureMethod == SignatureMethod.HmacSHA256)
            {
                using (var mac = new HMACSHA256(Encoding.UTF8.GetBytes(SecretKey)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(retStr));
                    requestParams.Add("Signature", Convert.ToBase64String(hash));
                    requestParams.Add("SignatureMethod", "HmacSHA256");
                }
            }
        }
Esempio n. 21
0
        public XElement Serialize()
        {
            var result = new XElement(Constants.XMLNamespaces.DS + "SignedInfo",
                                      CanonicalizationMethod.Serialize(),
                                      SignatureMethod.Serialize());

            foreach (var reference in References)
            {
                result.Add(reference.Serialize());
            }

            return(result);
        }
Esempio n. 22
0
        /// <summary>
        /// Get a page of membership.
        /// </summary>
        /// <param name="client">The HTTP client to use for this request.</param>
        /// <param name="serviceUrl">The membership service URL. In LTI 1 the parameter will be in the launch as <code>custom_context_membership</code>.</param>
        /// <param name="consumerKey">The OAuth Consumer Key.</param>
        /// <param name="consumerSecret">The OAuth Consumer Secret to use for signing the request.</param>
        /// <param name="limit">Specifies the maximum number of items that should be delivered per page. This parameter is merely a hint. The server is not obligated to honor this limit and may at its own discretion choose a different value for the number of items per page.</param>
        /// <param name="rlid">The ID of a resource link within the context and associated and the Tool Provider. The result set will be filtered so that it includes only those memberships that are permitted to access the resource link. If omitted, the result set will include all memberships for the context.</param>
        /// <param name="role">The role for a membership. The result set will be filtered so that it includes only those memberships that contain this role. The value of the parameter should be the full URI for the role, although the simple name may be used for context-level roles. If omitted, the result set will include all memberships with any role.</param>
        /// <param name="signatureMethod">The signatureMethod. Defaults to <see cref="SignatureMethod.HmacSha1"/></param>
        /// <param name="deserializationErrorHandler">A deserialization error handler. Defaults to null.</param>
        public static async Task <ClientResponse <MembershipContainerPage> > GetMembershipPageAsync(
            HttpClient client, string serviceUrl, string consumerKey, string consumerSecret,
            int?limit = null, string rlid = null, ContextRole?role = null, SignatureMethod signatureMethod = SignatureMethod.HmacSha1,
            EventHandler <Newtonsoft.Json.Serialization.ErrorEventArgs> deserializationErrorHandler = null)
        {
            var filteredServiceUrl = GetFilteredServiceUrl(serviceUrl, limit, rlid, role);

            return(await GetFilteredMembershipPageAsync
                   (
                       client, filteredServiceUrl, consumerKey, consumerSecret,
                       LtiConstants.LisMembershipContainerMediaType, signatureMethod,
                       deserializationErrorHandler
                   ).ConfigureAwait(false));
        }
        private void createSignature()
        {
            var method  = ContainedRequest.Method;
            var baseUrl = String.Format("{0}://{1}{2}", ContainedRequest.RequestUri.Scheme, ContainedRequest.RequestUri.Host, ContainedRequest.RequestUri.AbsolutePath);

            var parameters  = new SortedDictionary <string, string>(AuthorizationHeader);
            var queryParams = UrlHelper.ParseQueryString(ContainedRequest.RequestUri.Query);

            foreach (var pair in queryParams)
            {
                parameters.Add(pair.Key, pair.Value);
            }

            if (method.Equals("POST") && !String.IsNullOrEmpty(ContainedRequest.ContentType) && ContainedRequest.ContentType.Equals(FormUrlEncodedMimeType))
            {
                if (!String.IsNullOrEmpty(PostParameters))
                {
                    var postParams = UrlHelper.ParseQueryString(PostParameters);

                    foreach (var pair in postParams)
                    {
                        parameters.Add(pair.Key, pair.Value);
                    }
                }
            }

            var paramString = new StringBuilder();

            foreach (var pair in parameters)
            {
                if (paramString.Length > 0)
                {
                    paramString.Append("&");
                }
                paramString.AppendFormat("{0}={1}", UrlHelper.Encode(pair.Key), UrlHelper.Encode(pair.Value));
            }

            // percent encode everything
            var encodedParams = String.Format("{0}&{1}&{2}", ContainedRequest.Method.ToUpper(),
                                              UrlHelper.Encode(baseUrl), UrlHelper.Encode(paramString.ToString()));

            // key
            var key = String.Format("{0}&{1}", UrlHelper.Encode(RequestTokens.ConsumerSecret),
                                    UrlHelper.Encode(RequestTokens.AccessTokenSecret));

            // signature time!
            string signature = SignatureMethod.CreateSignature(this.SigningMethod, encodedParams.ToString(), key);

            AuthorizationHeader.Add("oauth_signature", signature);
        }
        protected override string ComputeSignatureCore(string key, string data)
        {
            Debug.Assert(!string.IsNullOrEmpty(data));
#if NETCOREAPP2_0
            using (var algorithm = new HMACSHA1())
#else
            using (var algorithm = KeyedHashAlgorithm.Create(SignatureMethod.ToUpperInvariant()))
#endif
            {
                algorithm.Key = Encoding.GetBytes(key.ToCharArray());
                return(Convert.ToBase64String(
                           algorithm.ComputeHash(Encoding.GetBytes(data.ToCharArray()))));
            }
        }
Esempio n. 25
0
        ///<summary>生成签名</summary>
        ///<param name="signStr">被加密串</param>
        ///<param name="secret">加密密钥</param>
        ///<returns>签名</returns>
        private static string SecretString(string signStr, string secret, SignatureMethod signatureMethod = SignatureMethod.sha1)
        {
            switch (signatureMethod)
            {
            case SignatureMethod.sha1:
                using (HMACSHA1 mac = new HMACSHA1(Encoding.UTF8.GetBytes(secret)))
                {
                    byte[] hash = mac.ComputeHash(Encoding.UTF8.GetBytes(signStr));
                    return(BitConverter.ToString(hash).Replace("-", "").ToLower());
                }

            default:
                throw new ArgumentException($"未知的签名加密类型{signatureMethod.ToString()}");
            }
        }
Esempio n. 26
0
        protected override string ComputeSignatureCore(string key, string data)
        {
            Debug.Assert(!string.IsNullOrEmpty(data));

            using (var algorithm = CreateAlgorithm(SignatureMethod.ToUpperInvariant(), Encoding.GetBytes(key.ToCharArray())))
            {
                return(Convert.ToBase64String(algorithm.ComputeHash(Encoding.GetBytes(data.ToCharArray()))));
            }

            //using (var algorithm = KeyedHashAlgorithm.Create(SignatureMethod.ToUpperInvariant()))
            //{
            //    algorithm.Key = Encoding.GetBytes(key.ToCharArray());
            //    return Convert.ToBase64String(
            //        algorithm.ComputeHash(Encoding.GetBytes(data.ToCharArray())));
            //}
        }
        public static ISignature GetSignature(SignatureMethod method)
        {
            var sig = default(ISignature);
            switch (method)
            {
                case SignatureMethod.HMAC_SHA1:
                    sig= new SHA1Signature();
                    break;
                case SignatureMethod.MD5:
                default:
                    sig= new MD5Signature();
                    break;
            }

            return sig;
        }
Esempio n. 28
0
        public Task<string> GetRequestTokenRequestAsync(
            string requestUrl,
            string consumerKey,
            string consumerSecret,
            string callbackUrl,
            SignatureMethod signatureMethod)
        {
            var requestTokenUrl = OAuthMessageBuilder.GetRequestTokenRequest(
                requestUrl,
                consumerKey,
                consumerSecret,
                callbackUrl,
                signatureMethod);

            return RequestAsync(requestTokenUrl);
        }
Esempio n. 29
0
        public virtual OAuthWebQueryInfo BuildProtectedResourceInfo(string method, WebParameterCollection parameters, string url)
        {
            ValidateProtectedResourceState();
            if (parameters == null)
            {
                parameters = new WebParameterCollection();
            }
            Uri uri = new Uri(url);
            NameValueCollection nameValueCollection = HttpUtility.ParseQueryString(uri.Query);

            string[] allKeys = nameValueCollection.AllKeys;
            foreach (string name in allKeys)
            {
                string text = method.ToUpperInvariant();
                if (text != null && text == "POST")
                {
                    parameters.Add(new HttpPostParameter(name, nameValueCollection[name]));
                }
                else
                {
                    parameters.Add(name, nameValueCollection[name]);
                }
            }
            string timestamp = OAuthTools.GetTimestamp();
            string nonce     = OAuthTools.GetNonce();

            AddAuthParameters(parameters, timestamp, nonce);
            string            signatureBase     = OAuthTools.ConcatenateRequestElements(method, url, parameters);
            string            signature         = OAuthTools.GetSignature(SignatureMethod, SignatureTreatment, signatureBase, ConsumerSecret, TokenSecret);
            OAuthWebQueryInfo oAuthWebQueryInfo = new OAuthWebQueryInfo();

            oAuthWebQueryInfo.WebMethod          = method;
            oAuthWebQueryInfo.ParameterHandling  = ParameterHandling;
            oAuthWebQueryInfo.ConsumerKey        = ConsumerKey;
            oAuthWebQueryInfo.Token              = Token;
            oAuthWebQueryInfo.SignatureMethod    = SignatureMethod.ToRequestValue();
            oAuthWebQueryInfo.SignatureTreatment = SignatureTreatment;
            oAuthWebQueryInfo.Signature          = signature;
            oAuthWebQueryInfo.Timestamp          = timestamp;
            oAuthWebQueryInfo.Nonce              = nonce;
            oAuthWebQueryInfo.Version            = (Version ?? "1.0");
            oAuthWebQueryInfo.Callback           = CallbackUrl;
            oAuthWebQueryInfo.ConsumerSecret     = ConsumerSecret;
            oAuthWebQueryInfo.TokenSecret        = TokenSecret;
            return(oAuthWebQueryInfo);
        }
Esempio n. 30
0
        public static ISignature GetSignature(SignatureMethod method)
        {
            var sig = default(ISignature);

            switch (method)
            {
            case SignatureMethod.HMAC_SHA1:
                sig = new SHA1Signature();
                break;

            case SignatureMethod.MD5:
            default:
                sig = new MD5Signature();
                break;
            }

            return(sig);
        }
Esempio n. 31
0
        public static string GetSignature(SignatureMethod method, string signatureBaseString, string clientSecret, string tokenSecret)
        {
            switch (method)
            {
            case SignatureMethod.PLAINTEXT:
                return(string.Format("{0}&{1}", OAuthPercentEncode(clientSecret), OAuthPercentEncode(tokenSecret)));

            case SignatureMethod.HMAC_SHA1:
                string   key      = string.Format("{0}&{1}", OAuthPercentEncode(clientSecret), OAuthPercentEncode(tokenSecret));
                HMACSHA1 hmacsha1 = new HMACSHA1(Encoding.ASCII.GetBytes(key));
                byte[]   digest   = hmacsha1.ComputeHash(Encoding.ASCII.GetBytes(signatureBaseString));
                return(Convert.ToBase64String(digest));

            case SignatureMethod.RSA_SHA1:
            default:
                throw new NotImplementedException();
            }
        }
Esempio n. 32
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);
            }
        }
Esempio n. 33
0
        private static string GenerateSignature(string consumerSecret, SignatureMethod signatureMethod, string signatureBaseString, string tokenSecret = null)
        {
            switch (signatureMethod)
            {
            case SignatureMethod.HMACSHA1:
                var hmacsha1 = new HMACSHA1();
                hmacsha1.Key = Encoding.ASCII.GetBytes(String.Format("{0}&{1}", UrlEncode(consumerSecret), String.IsNullOrEmpty(tokenSecret) ? "" : UrlEncode(tokenSecret)));
                return(ComputeHash(hmacsha1, signatureBaseString));

            case SignatureMethod.PLAINTEXT:
                throw new NotImplementedException("PLAINTEXT Signature Method type is not yet implemented");

            case SignatureMethod.RSASHA1:
                throw new NotImplementedException("RSA-SHA1 Signature Method type is not yet implemented");

            default:
                throw new ArgumentException("Unknown Signature Method", "signatureMethod");
            }
        }
Esempio n. 34
0
        private void AddXAuthParameters(ICollection <WebPair> parameters, string timestamp, string nonce)
        {
            WebParameterCollection webParameterCollection = new WebParameterCollection();

            webParameterCollection.Add(new WebPair("x_auth_username", ClientUsername));
            webParameterCollection.Add(new WebPair("x_auth_password", ClientPassword));
            webParameterCollection.Add(new WebPair("x_auth_mode", "client_auth"));
            webParameterCollection.Add(new WebPair("oauth_consumer_key", ConsumerKey));
            webParameterCollection.Add(new WebPair("oauth_signature_method", SignatureMethod.ToRequestValue()));
            webParameterCollection.Add(new WebPair("oauth_timestamp", timestamp));
            webParameterCollection.Add(new WebPair("oauth_nonce", nonce));
            webParameterCollection.Add(new WebPair("oauth_version", Version ?? "1.0"));
            WebParameterCollection webParameterCollection2 = webParameterCollection;

            foreach (WebPair item in webParameterCollection2)
            {
                parameters.Add(item);
            }
        }
Esempio n. 35
0
        public Task<string> GetGetAccessTokenRequestAsync(
            string requestUrl,
            string consumerKey,
            string consumerSecret,
            string tokenSecret,
            SignatureMethod signatureMethod,
            string oauth_token,
            string verifier)
        {
            var accessTokenUrl = OAuthMessageBuilder.GetGetAccessTokenRequest(
            requestUrl,
            consumerKey,
            consumerSecret,
            tokenSecret,
            signatureMethod,
            oauth_token,
            verifier);

            return RequestAsync(accessTokenUrl);
        }
Esempio n. 36
0
 private static string GenerateSignature(string consumerSecret, SignatureMethod signatureMethod, string signatureBaseString, string tokenSecret = null)
 {
     switch (signatureMethod) {
         case SignatureMethod.HMACSHA1:
             var hmacsha1 = new HMACSHA1();
             hmacsha1.Key = Encoding.ASCII.GetBytes(string.Format("{0}&{1}", Utils.UrlEncode(consumerSecret), string.IsNullOrEmpty(tokenSecret) ? "" : Utils.UrlEncode(tokenSecret)));
             return ComputeHash(hmacsha1, signatureBaseString);
         case SignatureMethod.Plaintext:
             throw new NotImplementedException("PLAINTEXT Signature Method type is not yet implemented");
         case SignatureMethod.RSASHA1:
             throw new NotImplementedException("RSA-SHA1 Signature Method type is not yet implemented");
         default:
             throw new ArgumentException("Unknown Signature Method", "signatureMethod");
     }
 }
Esempio n. 37
0
 /**
  * Creates a <code>SignedInfo</code> with the specified parameters.
  *
  * @param cm the canonicalization method
  * @param sm the signature method
  * @param references a list of one or more {@link Reference}s. The list is
  *    defensively copied to protect against subsequent modification.
  * @param id the id (may be <code>null</code>)
  * @return a <code>SignedInfo</code>
  * @throws ClassCastException if any of the references are not of
  *    type <code>Reference</code>
  * @throws IllegalArgumentException if <code>references</code> is empty
  * @throws NullPointerException if <code>cm</code>, <code>sm</code>, or
  *    <code>references</code> are <code>null</code>
  */
 public abstract SignedInfo newSignedInfo(CanonicalizationMethod cm,
 SignatureMethod sm, java.util.List<Object> references, String id);
Esempio n. 38
0
 /// <summary>
 /// Generate arguments for Token requests.
 /// </summary>
 /// <remarks>
 /// For Request tokens, leave tokenName and tokenSecret as null.
 /// For Accept tokens, leave args as null.
 /// </remarks>
 /// <param name="uri">Token operation URL.</param>
 /// <param name="postArgs">HTTP POST arguments to include in signature generation.</param>
 /// <param name="consumerKey">The consumer key.</param>
 /// <param name="consumerSecret">The consumer secret.</param>
 /// <param name="tokenName">The token key, if required.</param>
 /// <param name="tokenSecret">The token secret, if required.</param>
 /// <param name="sigMethod">Signature generation method.</param>
 /// <param name="method">HTTP method for the request.</param>
 /// <param name="rsaCert">The X509 certificate containing the private key used for RSA-SHA1.</param>
 /// <returns>All required arguments for the Token request.</returns>
 static NameValueCollection TokenArgs(Uri uri, NameValueCollection postArgs, string consumerKey, string consumerSecret, string tokenName, string tokenSecret, X509Certificate2 rsaCert, SignatureMethod sigMethod, string method)
 {
     NameValueCollection nvc = new NameValueCollection();
     if (postArgs != null) nvc.Add(postArgs);
     nvc[OAuthArguments.OAuthConsumerKey] = consumerKey;
     if (!String.IsNullOrEmpty(tokenName)) nvc[OAuthArguments.OAuthToken] = tokenName;
     nvc[OAuthArguments.OAuthSignatureMethod] = OAuthUtility.SigMethodToString(sigMethod);
     long tstamp = OAuthUtility.Timestamp();
     nvc[OAuthArguments.OAuthTimestamp] = tstamp.ToString(CultureInfo.InvariantCulture);
     nvc[OAuthArguments.OAuthNonce] = Nonce(tstamp);
     nvc[OAuthArguments.OAuthVersion] = "1.0";
     string sig = OAuthUtility.GenerateSignature(OAuthUtility.GenerateBaseString(uri, nvc, method), consumerSecret, tokenSecret, rsaCert, sigMethod);
     Trace.WriteLine(sig, "AuthSignature");
     nvc[OAuthArguments.OAuthSignature] = sig;
     // Additional arguments for signing should not be included in the authentication data.
     if (postArgs != null)
     {
         foreach (string key in postArgs.Keys)
         {
             nvc.Remove(key);
         }
     }
     return nvc;
 }
Esempio n. 39
0
 /// <summary>
 /// Upgrade a Request Token to an Access Token.
 /// </summary>
 /// <param name="uri">Access token URL.</param>
 /// <param name="token">RequestToken to upgrade.</param>
 /// <param name="consumerKey">The consumer key.</param>
 /// <param name="consumerSecret">The consumer secret.</param>
 /// <param name="sigMethod">The signature signing method.</param>
 /// <param name="mode">The HTTP connection and argument format to use.</param>
 /// <param name="rsaCert">The X509 certificate containing the private key used for RSA-SHA1.</param>
 /// <returns>A populated AccessToken.</returns>
 static AccessToken GetAccessToken(Uri uri, RequestToken token, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, SignatureMethod sigMethod, AuthenticationMethod mode)
 {
     NameValueCollection nvc = TokenArgs(uri, null, consumerKey, consumerSecret, token.Key, token.Secret, rsaCert, sigMethod, AuthenticationMethodToString(mode));
     WebResponse response = Request(uri, nvc, mode);
     NameValueCollection rparams = FormatResponse(response);
     return new AccessToken(rparams);
 }
Esempio n. 40
0
 public String SignatureMethodString(SignatureMethod s)
 {
     String x = String.Empty;
     switch (s) {
     case SignatureMethod.HmacSha1:
         x = "HMAC-SHA1";
         break;
     case SignatureMethod.RsaSha1:
         x = "RSA-SHA1";
         break;
     case SignatureMethod.Plaintext:
         x = "PLAINTEXT";
         break;
     }
     return x;
 }
Esempio n. 41
0
 /// <summary>
 /// Get a new RequestToken from the service provider.
 /// </summary>
 /// <param name="uri">Request token URL.</param>
 /// <param name="args">Arguments to include in the request.</param>
 /// <param name="consumerKey">The consumer key.</param>
 /// <param name="consumerSecret">The consumer secret.</param>
 /// <param name="sigMethod">The signature signing method.</param>
 /// <param name="mode">The HTTP connection and argument format to use.</param>
 /// <param name="rsaCert">The X509 certificate containing the private key for RSA-SHA1.</param>
 /// <returns>A populated Request Token.</returns>
 static RequestToken GetRequestToken(Uri uri, NameValueCollection args, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, SignatureMethod sigMethod, AuthenticationMethod mode)
 {
     NameValueCollection nvc = TokenArgs(uri, args, consumerKey, consumerSecret, null, null, rsaCert, sigMethod, AuthenticationMethodToString(mode));
     WebResponse response = Request(uri, nvc, mode);
     NameValueCollection rnvc = FormatResponse(response);
     return new RequestToken(rnvc);
 }
Esempio n. 42
0
        public static string Request(HttpMethod httpMethod, Uri uri, List<Parameter> parameters, string consumerKey, string consumerSecret, string token, string tokenSecret, SignatureMethod signatureMethod = SignatureMethod.HMACSHA1)
        {
            try {
                return OAuth.Request(httpMethod, uri, parameters, consumerKey, consumerSecret, token, tokenSecret, signatureMethod);
            }
            catch (OpenAuthException ex) {
                switch (ex.HttpStatusCode) {
                    case HttpStatusCode.BadRequest:
                        ex.Error = OpenAuthErrorType.InvalidOrExpiredAccessToken;
                        break;
                }

                throw ex;
            }
        }
Esempio n. 43
0
 public static string Request(HttpMethod httpMethod, Uri uri, List<Parameter> parameters, string consumerKey, string consumerSecret, string token, string tokenSecret, SignatureMethod signatureMethod = SignatureMethod.HMACSHA1)
 {
     try {
         return OAuth.Request(httpMethod, uri, parameters, consumerKey, consumerSecret, token, tokenSecret, signatureMethod);
     }
     catch (OpenAuthException ex) {
         throw ex;
     }
 }
Esempio n. 44
0
        /// <summary>
        /// Get authentication parameters to access an OAuth
        /// protected resource.  Used for two-legged OAuth.
        /// </summary>
        /// <param name="uri">Destination URL.</param>
        /// <param name="requestorId">Name of the user account at the remote site.</param>
        /// <param name="arguments">Arguments to include in the request.</param>
        /// <param name="consumerKey">The consumer key.</param>
        /// <param name="consumerSecret">The consumer secret.</param>
        /// <param name="format">The format of the resulting string.</param>
        /// <param name="method">HTTP method that will be used during the request.</param>
        /// <param name="rsaCert">The X509 certificate containing the private key used for RSA-SHA1.</param>
        /// <param name="sigMethod">Signature signing method.</param>
        /// <returns>String containing all authentication parameters, in the specified format.</returns>
        internal static string GetAuthParameters(Uri uri, string requestorId, NameValueCollection arguments, string consumerKey, string consumerSecret, X509Certificate2 rsaCert, AuthenticationMethod format, string method, SignatureMethod sigMethod)
        {
            NameValueCollection sigColl = new NameValueCollection();
            if (arguments != null) sigColl.Add(arguments);
            sigColl[OAuthArguments.XOAuthRequestorId] = requestorId;

            NameValueCollection queryArgs = HttpUtility.ParseQueryString(uri.Query);
            sigColl.Add(queryArgs);
            NameValueCollection nvc = TokenArgs(uri, sigColl, consumerKey, consumerSecret, null, null, rsaCert, sigMethod, method);

            foreach (string key in queryArgs.Keys)
            {
                nvc.Remove(key);
            }

            return OAuthUtility.ArgsToVal(nvc, format);
        }
Esempio n. 45
0
        public static string Request(HttpMethod httpMethod, Uri uri, List<Parameter> parameters, string consumerKey, string consumerSecret, string token, string tokenSecret, SignatureMethod signatureMethod = SignatureMethod.HMACSHA1)
        {
            var timestamp = GenerateTimeStamp();
            var nonce = GenerateNonce(timestamp);

            var headerParameters = parameters != null ? new List<Parameter>(parameters) : new List<Parameter>();
            headerParameters.Add(new Parameter(OAuthParameter.ConsumerKey.Value(), consumerKey));
            headerParameters.Add(new Parameter(OAuthParameter.SignatureMethod.Value(), signatureMethod.Value()));
            headerParameters.Add(new Parameter(OAuthParameter.Timestamp.Value(), timestamp));
            headerParameters.Add(new Parameter(OAuthParameter.Nonce.Value(), nonce));
            headerParameters.Add(new Parameter(OAuthParameter.Version.Value(), OAuthVersion));
            headerParameters.Add(new Parameter(OAuthParameter.Token.Value(), token));

            string signatureBaseString = GenerateSignatureBaseString(httpMethod, uri, headerParameters);
            string signature = GenerateSignature(consumerSecret, signatureMethod, signatureBaseString, tokenSecret);
            string header = GenerateHeader(consumerKey, signatureMethod.Value(), signature, timestamp, nonce, OAuthVersion, null, token);

            return Utils.Request(httpMethod, uri, parameters, header);
        }
Esempio n. 46
0
        public static OpenAuthRequestToken GetRequestToken(Uri uri, string consumerKey, string consumerSecret, string callbackUrl, SignatureMethod signatureMethod = SignatureMethod.HMACSHA1)
        {
            var urlEncodedCallback = Utils.UrlEncode(callbackUrl);
            var timestamp = GenerateTimeStamp();
            var nonce = GenerateNonce(timestamp);

            var parameters = new List<Parameter>();
            parameters.Add(new Parameter(OAuthParameter.ConsumerKey.Value(), consumerKey));
            parameters.Add(new Parameter(OAuthParameter.SignatureMethod.Value(), signatureMethod.Value()));
            parameters.Add(new Parameter(OAuthParameter.Timestamp.Value(), timestamp));
            parameters.Add(new Parameter(OAuthParameter.Nonce.Value(), nonce));
            parameters.Add(new Parameter(OAuthParameter.Version.Value(), OAuthVersion));
            parameters.Add(new Parameter(OAuthParameter.Callback.Value(), callbackUrl));

            string signatureBaseString = GenerateSignatureBaseString(HttpMethod.Post, uri, parameters);
            string signature = GenerateSignature(consumerSecret, signatureMethod, signatureBaseString);
            string header = GenerateHeader(consumerKey, signatureMethod.Value(), signature, timestamp, nonce, OAuthVersion, callbackUrl);

            string response = Utils.Request(HttpMethod.Post, uri, header);
            NameValueCollection data = HttpUtility.ParseQueryString(response);
            if (!data.AllKeys.Contains(OAuthParameter.Token.Value()) ||
                !data.AllKeys.Contains(OAuthParameter.TokenSecret.Value()) ||
                !data.AllKeys.Contains(OAuthParameter.CallbackConfirmed.Value()))
                throw new OpenAuthException { Error = OpenAuthErrorType.MissingKeys };

            return new OpenAuthRequestToken {
                Token = data[OAuthParameter.Token.Value()],
                TokenSecret = data[OAuthParameter.TokenSecret.Value()]
            };
        }
Esempio n. 47
0
 public string GetRefreshAccessTokenRequest(string requestUrl, string consumerKey, string consumerSecret, SignatureMethod signatureMethod, string accessToken, string accessTokenSecret)
 {
     var refreshAccessTokenUrl = OAuthMessageBuilder.GetRefreshAccessTokenRequest(
        requestUrl,
        consumerKey,
        consumerSecret,
        accessToken,
        signatureMethod,
        accessTokenSecret);
     return Request(refreshAccessTokenUrl);
 }
Esempio n. 48
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="secretKey"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        public static bool Valid(HecpRequest request, string secretKey, SignatureMethod method)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            var credential = request.Credential;

            switch (method)
            {
                case SignatureMethod.Undefined:
                    return false;
                case SignatureMethod.HMAC_SHA1:
                    return credential.Password == Signature.Sign(request.ToOrignalString(request.Credential.CredentialData), secretKey);
                default:
                    return false;
            }
        }
Esempio n. 49
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OAuth"/> class.
        /// </summary>
        /// <param name="consumerCredential">
        /// The consumer credential.
        /// </param>
        /// <param name="serviceProviderDescription">
        /// The service provider description.
        /// </param>
        /// <param name="signatureMethod">
        /// The signature method.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public OAuth(ConsumerCredential consumerCredential,
                     ServiceProviderDescription serviceProviderDescription,
                     SignatureMethod signatureMethod = SignatureMethod.HmacSha1)
        {
            if (consumerCredential == null)
            {
                throw new ArgumentNullException("consumerCredential");
            }

            if (serviceProviderDescription == null)
            {
                throw new ArgumentNullException("serviceProviderDescription");
            }

            this._Realm                 = String.Empty;
            this._ConsumerCredential    = consumerCredential;
            this._SignatureMethod       = signatureMethod;
            this._ServiceProviderDescription = serviceProviderDescription;

            this.LogEnabled     = false;
            this.LogIndentSize  = 4;
            this.UserAgent      = "Mirai";
        }