Exemplo n.º 1
0
        public OAuthRequestToken(
            string token,
            string secret,
            IConsumer consumer,
            TokenStatus status,
            OAuthParameters associatedParameters,
            IIdentity authenticatedUser,
            string[] roles)
            : this()
        {
            if (string.IsNullOrEmpty(token))
                throw new ArgumentException("token must not be null or empty", "token");

            if (secret == null)
                throw new ArgumentNullException("secret", "secret must not be null");

            if (consumer == null)
                throw new ArgumentNullException("consumer", "consumer must not be null");

            if (roles == null)
                throw new ArgumentNullException("roles", "roles must not be null");

            this.Token = token;
            this.Secret = secret;
            this.Status = status;
            this.ConsumerKey = consumer.Key;
            this.AssociatedParameters = associatedParameters;
            this.AuthenticatedUser = authenticatedUser;
            this.Roles = roles;
        }
Exemplo n.º 2
0
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestProperty = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;

            NameValueCollection rawParameters = HttpUtility.ParseQueryString(request.Headers.To.Query);
            UriBuilder uriBuilder = new UriBuilder(request.Headers.To);
            uriBuilder.Query = Rfc3986.EncodeAndJoin(rawParameters);

            request.Headers.To = uriBuilder.Uri;

            OAuthConsumer consumer = new OAuthConsumer(_credentials.OAuthKey, _credentials.OAuthSecret);

            int unixTime = UnixTime.ToUnixTime(DateTime.UtcNow);

            OAuthParameters parameters = new OAuthParameters();
            parameters.Version = Constants.Version1_0;
            parameters.SignatureMethod = "RSA-SHA1";
            parameters.ConsumerKey = _credentials.OAuthKey;
            parameters.Token = _credentials.OAuthToken;
            parameters.TokenSecret = _credentials.OAuthTokenSecret;
            parameters.Timestamp = unixTime.ToString();
            parameters.Nonce = _nonceProvider.GenerateNonce(unixTime);

            RsaSha1SigningProvider provider = new RsaSha1SigningProvider();
            provider.PfxFile = _credentials.OAuthPfxFile;
            provider.PfxPassword = _credentials.OAuthPfxPassword;

            parameters.Sign(request.Headers.To, httpRequestProperty.Method, consumer, null, provider);

            httpRequestProperty.Headers["Authorization"] = parameters.ToHeaderFormat();

            return null;
        }
        public void Test_SignatureCompareWithSpaceInSignature()
        {
            OAuthParameters parameters = new OAuthParameters()
            {
                ConsumerKey = "key",
                Nonce = "5b434e59-729a-444b-9a11-2d8e57b1f2fb",
                SignatureMethod = "HMAC-SHA1",
                Timestamp = "1251983826",                
                Version = "1.0",
                Callback = "http://yourownsite.com/"
            };

            string sigbase = SignatureBase.Create(
                "GET",
                new Uri("http://localhost:3423/request-token.ashx"),
                parameters);

            string consumerSecret = "secret";
            string tokenSecret = null;

            HmacSha1SigningProvider signingProvider = new HmacSha1SigningProvider();
            Assert.That(signingProvider.SignatureMethod, Is.EqualTo("HMAC-SHA1"));

            string hash = signingProvider.ComputeSignature(sigbase, consumerSecret, tokenSecret);
            Assert.That(hash, Is.EqualTo("zHTiQHg8X5Lpkh+/0MSatKeNEFg="));

            Assert.That(signingProvider.CheckSignature(sigbase, Rfc3986.Decode("zHTiQHg8X5Lpkh+/0MSatKeNEFg="), consumerSecret, tokenSecret), "Signature did not match");

        }
Exemplo n.º 4
0
        public void TestCase()
        {
            ISigningProvider rsa = new RsaSha1SigningProvider()
            {
                // PFX file is copied to output directory
                PfxFile = @"WikiTests\testcase.rsa.pfx"
            };

            OAuthParameters parameters = new OAuthParameters()
            {
                SignatureMethod = "RSA-SHA1",
                Version = Constants.Version1_0,
                ConsumerKey = "dpf43f3p2l4k3l03",
                Timestamp = "1196666512",
                Nonce = "13917289812797014437"
            };
            parameters.AdditionalParameters.Add("file", "vacaction.jpg");
            parameters.AdditionalParameters.Add("size", "original");

            Uri baseUri = new Uri("http://photos.example.net/photos");

            string sigbase = SignatureBase.Create(
                "GET", 
                baseUri, 
                parameters);

            Assert.That(sigbase, Is.EqualTo("GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacaction.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3D13917289812797014437%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1196666512%26oauth_version%3D1.0%26size%3Doriginal"));

            parameters.Signature = rsa.ComputeSignature(sigbase, "kd94hf93k423kf44", null);

            Assert.That(parameters.Signature, Is.EqualTo("jvTp/wX1TYtByB1m+Pbyo0lnCOLIsyGCH7wke8AUs3BpnwZJtAuEJkvQL2/9n4s5wUmUl4aCI4BwpraNx4RtEXMe5qg5T1LVTGliMRpKasKsW//e+RinhejgCuzoH26dyF8iY2ZZ/5D1ilgeijhV/vBka5twt399mXwaYdCwFYE="));

            // There is no point comparing the URLs because order is not query string parameter important in URLs
        }
        public void TestAEqualsB()
        {
            OAuthParameters parameters = new OAuthParameters();
            parameters.AdditionalParameters.Add("a", "b");

            Assert.That(parameters.ToNormalizedString(), Is.EqualTo("a=b"));
        }
Exemplo n.º 6
0
        private string ToBaseString(Request request, OAuthParameters parameters)
        {
            if (String.IsNullOrEmpty(request.ContentType))
                throw new ArgumentException(
                    "It should really specify the content type otherwise we can't " +
                    "decide whether or not to include parameters in signature.", "request"
                );

            // TODO: Perhaps this class should be collecting the parameters from the URI
            //
            // http://oauth.net/core/1.0/#anchor14 9.1.1
            // The request parameters are collected, sorted and concatenated into a normalized string:
            //
            // Parameters in the OAuth HTTP Authorization header excluding the realm parameter.
            // Parameters in the HTTP POST request body (with a content-type of application/x-www-form-urlencoded).
            // HTTP GET parameters added to the URLs in the query part (as defined by [RFC3986] section 3).

            // [2011-07-08, BJB]: This implies we ought to be collecting them all.
            // The request contains all of this stuff - it's just that we're treating URI and
            // parameters separately further up.

            // You can tell if there is a body or not by checking the existence of Content-length -- but our
            // requests are not fully-formed enough -- we don't have concept of body.
            un.less(() => ParameterInclusionPolicy.IncludeParameters(request), () =>
                parameters.AdditionalParameters.Clear()
            );

            return SignatureBase.Create(request.RequestLine.Verb, request.RequestLine.Uri, parameters);
        }
Exemplo n.º 7
0
    private HttpWebRequest GenerateRequest(string contentType, string requestMethod)
    {
      var ts = UnixTime.ToUnixTime(DateTime.Now);
      //Create the needed OAuth Parameters. 
      //Refer - http://oauth.net/core/1.0/#sig_base_example
      var param = new OAuthParameters() {
        ConsumerKey = _consumerKey,
        SignatureMethod = SigningProvider.SignatureMethod,
        Version = Constants.Version1_0,
        Nonce = NonceProvider.GenerateNonce(ts),
        Timestamp = ts.ToString(),
      };

      //Generate Signature Hash
      var signatureBase = SignatureBase.Create(requestMethod.ToUpper(), _serviceProviderUri, param);
      //Set Signature Hash as one of the OAuth Parameter
      param.Signature = SigningProvider.ComputeSignature(signatureBase, _consumerSecret, null);

      var httpWebRequest = (HttpWebRequest)WebRequest.Create(_serviceProviderUri);
      httpWebRequest.Method = requestMethod;
      httpWebRequest.ContentType = contentType;
      httpWebRequest.Timeout = RequestTimeOut;
      //Add the OAuth Parameters to Authorization Header of Request
      httpWebRequest.Headers.Add(Constants.AuthorizationHeaderParameter, param.ToHeaderFormat());
      return httpWebRequest;
    }
        public void TestAEqualsXBangYAndAEqualsXSpaceY()
        {
            OAuthParameters parameters = new OAuthParameters();
            parameters.AdditionalParameters.Add("a", "x!y");
            parameters.AdditionalParameters.Add("a", "x y");

            Assert.That(parameters.ToNormalizedString(), Is.EqualTo("a=x%20y&a=x%21y"));
        }
        public void TestNameParamNoValue()
        {
            OAuthParameters parameters = new OAuthParameters();

            // NB: HttpRequest parses "name=" as { "name", string.Empty }
            parameters.AdditionalParameters.Add("name", string.Empty);

            Assert.That(parameters.ToNormalizedString(), Is.EqualTo("name="));
        }
        public void TestGetHttpExampleDotComWithSlashWithNEqualsV()
        {
            OAuthParameters parameters = new OAuthParameters();
            parameters.AdditionalParameters.Add("n", "v");

            Assert.That(
                SignatureBase.Create("GET", new Uri("http://example.com/"), parameters),
                Is.EqualTo("GET&http%3A%2F%2Fexample.com%2F&n%3Dv"));
        }
Exemplo n.º 11
0
        public String Sign(
            Request request,
            String consumerSecret,
            String tokenSecret,
            OAuthParameters parameters
            )
        {
            var baseString = ToBaseString(request, parameters);

            return new HmacSha1SigningProvider().ComputeSignature(baseString, consumerSecret, tokenSecret);
        }
Exemplo n.º 12
0
 /// <summary>
 /// Create a new request token
 /// </summary>
 /// <param name="consumer">The consumer for whom the token is to be created</param>
 /// <param name="parameters">The parameters that were sent in the request that
 /// created this token (both OAuth and additional parameters).</param>
 /// <returns>A request token</returns>
 public virtual IRequestToken CreateRequestToken(IConsumer consumer, OAuthParameters parameters)
 {
     return new OAuthRequestToken(
         GuidHelper.CreateGuid().ToString("D"),
         GuidHelper.CreateGuid().ToString("D"),
         consumer,
         TokenStatus.Unauthorized,
         parameters,
         null,
         new string[] { });
 }
Exemplo n.º 13
0
        public OAuthParameters Clone()
        {
            var clone = new OAuthParameters();

            foreach (KeyValuePair <string, string> item in this.parameters)
            {
                clone.parameters[item.Key] = item.Value;
            }

            clone.AdditionalParameters = new NameValueCollection(this.AdditionalParameters);

            return(clone);
        }
Exemplo n.º 14
0
 private String Sign(
     Request request,
     CredentialSet credentials,
     OAuthParameters parameters
     )
 {
     return new MadgexSignature().Sign(
         request,
         credentials.Consumer.Secret,
         credentials.Token.Secret,
         parameters
     );
 }
        public void TestPostHttpsPhotosDotExampleDotNetSlashRequestUnderscoreTokenWithOAuthParameters()
        {
            OAuthParameters parameters = new OAuthParameters()
            {
                Version = Constants.Version1_0,
                ConsumerKey = "dpf43f3p2l4k3l03",
                Timestamp = "1191242090",
                Nonce = "hsu94j3884jdopsl",
                SignatureMethod = "PLAINTEXT",
                Signature = "ignored"
            };

            Assert.That(
                SignatureBase.Create("POST", new Uri("https://photos.example.net/request_token"), parameters),
                Is.EqualTo("POST&https%3A%2F%2Fphotos.example.net%2Frequest_token&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dhsu94j3884jdopsl%26oauth_signature_method%3DPLAINTEXT%26oauth_timestamp%3D1191242090%26oauth_version%3D1.0"));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Parses the OAuth parameters from a HttpWebResponse.
        /// </summary>
        /// <param name="response">The Http response</param>
        /// <returns>
        /// An OAuthParameters object containing the parsed reserved OAuth parameters and any additional, valid parameters.</returns>
        public static OAuthParameters Parse(HttpWebResponse response)
        {
            if (response == null)
            {
                return(null);
            }

            NameValueCollection bodyParams = new NameValueCollection();

            using (MemoryStream ms = new MemoryStream())
            {
                System.IO.Stream stream = response.GetResponseStream();
                byte[]           buffer = new byte[32768];

                int read;

                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }

                Encoding bodyEncoding = Encoding.ASCII;
                if (!String.IsNullOrEmpty(response.ContentEncoding))
                {
                    bodyEncoding = Encoding.GetEncoding(response.ContentEncoding);
                }

                string responseBody = bodyEncoding.GetString(ms.ToArray());

                string[] nameValuePairs = responseBody.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string nameValuePair in nameValuePairs)
                {
                    string[] nameValuePairParts = nameValuePair.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                    if (nameValuePairParts.Length == 2)
                    {
                        bodyParams.Add(HttpUtility.UrlDecode(nameValuePairParts[0]), HttpUtility.UrlDecode(nameValuePairParts[1]));
                    }
                }

                if (bodyParams.Count == 0 && responseBody.Trim().Length > 0)
                {
                    bodyParams.Add(OAuthRequestExceptionParameters.Problem, responseBody);
                }
            }

            return(OAuthParameters.DoParse(null, response.Headers[Constants.WwwAuthenticateHeaderParameter], bodyParams, null, OAuthParameterSources.ConsumerDefault, false));
        }
Exemplo n.º 17
0
        public static string Create(string httpMethod, Uri requestUrl, OAuthParameters parameters)
        {
            StringBuilder sigbase = new StringBuilder();

            // Http header
            sigbase.Append(Rfc3986.Encode(httpMethod)).Append("&");

            // Normalized request URL
            sigbase.Append(Rfc3986.Encode(requestUrl.Scheme));
            sigbase.Append(Rfc3986.Encode("://"));
            sigbase.Append(Rfc3986.Encode(requestUrl.Authority.ToLowerInvariant()));
            sigbase.Append(Rfc3986.Encode(requestUrl.AbsolutePath));
            sigbase.Append("&");
            
            // Normalized parameters
            sigbase.Append(Rfc3986.Encode(parameters.ToNormalizedString(
                    Constants.RealmParameter,
                    Constants.SignatureParameter,
                    Constants.TokenSecretParameter)));

            return sigbase.ToString();
        }
Exemplo n.º 18
0
        public static string Create(string httpMethod, Uri requestUrl, OAuthParameters parameters)
        {
            StringBuilder sigbase = new StringBuilder();

            // Http header
            sigbase.Append(Rfc3986.Encode(httpMethod)).Append("&");

            // Normalized request URL
            sigbase.Append(Rfc3986.Encode(requestUrl.Scheme));
            sigbase.Append(Rfc3986.Encode("://"));
            sigbase.Append(Rfc3986.Encode(requestUrl.Authority.ToLowerInvariant()));
            sigbase.Append(Rfc3986.Encode(requestUrl.AbsolutePath));
            sigbase.Append("&");

            // Normalized parameters
            sigbase.Append(Rfc3986.Encode(parameters.ToNormalizedString(
                                              Constants.RealmParameter,
                                              Constants.SignatureParameter,
                                              Constants.TokenSecretParameter)));

            return(sigbase.ToString());
        }
Exemplo n.º 19
0
        public Uri BuildRequestTokenUri()
        {
            int timestamp = UnixTime.ToUnixTime(DateTime.Now);

            OAuthParameters parameters = new OAuthParameters();
            parameters.ConsumerKey = ConsumerStore.FixedConsumer.Key;
            parameters.Nonce = new GuidNonceProvider().GenerateNonce(timestamp);
            parameters.SignatureMethod = "HMAC-SHA1";
            parameters.Timestamp = timestamp.ToString(CultureInfo.InvariantCulture);
            parameters.Version = "1.0";
            parameters.Callback = "http://yourownsite.com/";

            parameters.Signature = ServiceProviderContext.GetSigningProvider("HMAC-SHA1").ComputeSignature(
                SignatureBase.Create("GET", this.RequestTokenBaseUri, parameters),
                ConsumerStore.FixedConsumer.Secret,
                null);

            UriBuilder builder = new UriBuilder(this.RequestTokenBaseUri) 
            { 
                Query = parameters.ToQueryStringFormat() 
            };
                
            return builder.Uri;
        }
        public void TestXBangYEqualsAAndXEqualsA()
        {
            OAuthParameters parameters = new OAuthParameters();
            parameters.AdditionalParameters.Add("x!y", "a");
            parameters.AdditionalParameters.Add("x", "a");

            Assert.That(parameters.ToNormalizedString(), Is.EqualTo("x=a&x%21y=a"));
        }
        public void TestGetHttpPhotosDotExampleDotNetSlashPhotosWithOAuthParametersAndFileEqualsVacationDotJpgAndSizeEqualsOriginal()
        {
            OAuthParameters parameters = new OAuthParameters()
            {
                Version = Constants.Version1_0,
                ConsumerKey = "dpf43f3p2l4k3l03",
                Token = "nnch734d00sl2jdk",
                Timestamp = "1191242096",
                Nonce = "kllo9940pd9333jh",
                SignatureMethod = "HMAC-SHA1",
                Signature = "ignored"
            };
            parameters.AdditionalParameters.Add("file", "vacation.jpg");
            parameters.AdditionalParameters.Add("size", "original");

            Assert.That(
                SignatureBase.Create("GET", new Uri("http://photos.example.net/photos"), parameters),
                Is.EqualTo("GET&http%3A%2F%2Fphotos.example.net%2Fphotos&file%3Dvacation.jpg%26oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_token%3Dnnch734d00sl2jdk%26oauth_version%3D1.0%26size%3Doriginal"));
        }
Exemplo n.º 22
0
        public void Test_FunnyCharacters()
        {
            OAuthParameters parameters = new OAuthParameters()
            {
                ConsumerKey = "weitu.googlepages.com",
                Nonce = "face868c-04a9-4e75-9534-0b58616c351c",
                SignatureMethod = "RSA-SHA1",
                Timestamp = "1213351382",
                Token = "1/rTf4q3P05rP2xv2xP1ls8mATiaQZnWPB51nTvo8n9Sw",
                Version = "1.0"
            };

            string basesig = SignatureBase.Create(
                "GET",
                new Uri("http://www.google.com/m8/feeds/contacts/default/base"),
                parameters);

            Assert.That(basesig, Is.EqualTo("GET&http%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2Fcontacts%2Fdefault%2Fbase&oauth_consumer_key%3Dweitu.googlepages.com%26oauth_nonce%3Dface868c-04a9-4e75-9534-0b58616c351c%26oauth_signature_method%3DRSA-SHA1%26oauth_timestamp%3D1213351382%26oauth_token%3D1%252FrTf4q3P05rP2xv2xP1ls8mATiaQZnWPB51nTvo8n9Sw%26oauth_version%3D1.0"));
        }
Exemplo n.º 23
0
        public OAuthParameters Clone()
        {
            var clone = new OAuthParameters();

            foreach (KeyValuePair<string, string> item in this.parameters)
                clone.parameters[item.Key] = item.Value;

            clone.AdditionalParameters = new NameValueCollection(this.AdditionalParameters);

            return clone;
        }
Exemplo n.º 24
0
        protected virtual void SignParameters(Uri requestUri, string httpMethod, OAuthParameters authParameters, IToken token)
        {
            // Check there is a signing provider for the signature method
            ISigningProvider signingProvider = this.Service.ComponentLocator.GetInstance<ISigningProvider>(Constants.SigningProviderIdPrefix + this.Service.SignatureMethod);

            if (signingProvider == null)
            {
                // There is no signing provider for this signature method
                OAuthRequestException.ThrowSignatureMethodRejected(null);
            }

            // Double check the signing provider declares that it can handle the signature method
            if (!signingProvider.SignatureMethod.Equals(this.Service.SignatureMethod))
                OAuthRequestException.ThrowSignatureMethodRejected(null);

            // Compute the signature
            authParameters.Sign(requestUri, httpMethod, this.Service.Consumer, token, signingProvider);
        }
Exemplo n.º 25
0
 public IRequestToken CreateRequestToken(IConsumer consumer, OAuthParameters parameters)
 {
     return TokenGenerator.FixedRequestToken;
 }
Exemplo n.º 26
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestUri"></param>
        /// <param name="authParameters"></param>
        /// <param name="httpMethod"></param>
        /// <param name="contentType"></param>
        /// <param name="bodyStream"></param>
        /// <returns></returns>
        protected virtual HttpWebRequest CreateRequest(Uri requestUri, OAuthParameters authParameters, string httpMethod, string contentType, System.IO.Stream bodyStream)
        {
            NameValueCollection requestSpecificParameters = new NameValueCollection(authParameters.AdditionalParameters);
            if (!this.Service.UseAuthorizationHeader)
            {
                ////The OAuth params need to be added either into the querystring or into the post body.
                requestSpecificParameters.Add(authParameters.OAuthRequestParams());
            }

            if (Constants.HttpPostUrlEncodedContentTypeRegex.IsMatch(contentType) && bodyStream == null)
            {
                ////All the requestSpecificParameters need to be encoded into the body bytes
                string body = Rfc3986.EncodeAndJoin(requestSpecificParameters);
                bodyStream = new MemoryStream(Encoding.ASCII.GetBytes(body));
            }
            else
            {
                ////They go into the querystring.
                string query = Rfc3986.EncodeAndJoin(requestSpecificParameters);

                if (!string.IsNullOrEmpty(query))
                {
                    UriBuilder mutableRequestUri = new UriBuilder(requestUri);
                    if (string.IsNullOrEmpty(mutableRequestUri.Query))
                        mutableRequestUri.Query = query;
                    else
                        mutableRequestUri.Query = mutableRequestUri.Query.Substring(1) + "&" + query;

                    requestUri = mutableRequestUri.Uri;
                }
            }

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUri);
            request.Method = httpMethod;

            if (this.Service.UseAuthorizationHeader)
                request.Headers.Add(HttpRequestHeader.Authorization, authParameters.ToHeaderFormat());

            if (!String.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;

                if (bodyStream != null)
                {
                    if (bodyStream.CanSeek) 
                        request.ContentLength = bodyStream.Length;

                    StreamCopier.CopyTo(bodyStream, request.GetRequestStream());
                }
            }

            return request;
        }
Exemplo n.º 27
0
        private OAuthParameters CreateOAuthParameters(NameValueCollection additionalParameters)
        {
            int timestamp = UnixTime.ToUnixTime(DateTime.Now);

            OAuthParameters authParameters = new OAuthParameters()
            {
                ConsumerKey = this.Service.Consumer.Key,
                Realm = this.Service.Realm,
                SignatureMethod = this.Service.SignatureMethod,
                Timestamp = timestamp.ToString(CultureInfo.InvariantCulture),
                Nonce = this.Service.ComponentLocator.GetInstance<INonceProvider>().GenerateNonce(timestamp),
                Version = this.Service.OAuthVersion
            };

            if (additionalParameters != null && additionalParameters.Count > 0)
                authParameters.AdditionalParameters.Add(additionalParameters);

            return authParameters;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Parses the OAuth parameters from a NameValueCollection
 /// </summary>
 /// <param name="parameterCollection">the NameValueCollection</param>
 /// <returns>
 /// An OAuthParameters object containing the parsed reserved OAuth parameters and any additional, valid parameters.</returns>
 public static OAuthParameters Parse(NameValueCollection parameterCollection)
 {
     return(OAuthParameters.DoParse(null, null, parameterCollection, null, OAuthParameterSources.HttpPostBody, true));
 }
Exemplo n.º 29
0
        //// TODO: ThrowAdditionalAuthorizationRequired
        //// TODO: ThrowPermissionUnknown
        //// TODO: ThrowPermissionDenied
        //// TODO: ThrowUserRefused

        /// <summary>
        /// Tries to parse an OAuthRequestException from some OAuth parameters. If an exception
        /// is indicated, the exception will be re-thrown.
        /// </summary>
        /// 
        /// <remarks>
        /// <para>
        /// If no exception is indicated, this method will return without throwing.
        /// </para>
        /// 
        /// <para>
        /// This will handle future <a href="http://wiki.oauth.net/ProblemReporting">Problem 
        /// Reporting</a> problem types, but not future additional parameters.
        /// </para>
        /// </remarks>
        /// 
        /// <example>
        /// This example shows how to rethrow an OAuth exception transmitted in a HTTP response.
        /// 
        /// <code lang="C#" numberLines="true">
        /// HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        /// OAuthParameters responseParameters = OAuthParameters.Parse(response);
        /// OAuthRequestException.TryRethrow(responseParameters);
        /// </code>
        /// </example>
        /// 
        /// <param name="parameters">The OAuth parameters</param>
        /// 
        /// <exception cref="OAuth.Net.Common.OAuthRequestException">
        /// If the OAuth parameters indicate an OAuth exception
        /// </exception>
        public static void TryRethrow(OAuthParameters parameters)
        {
            if (parameters == null || parameters.AdditionalParameters == null)
                return;

            if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.Problem]))
            {
                OAuthRequestException ex = new OAuthRequestException()
                {
                    Problem = parameters.AdditionalParameters[OAuthRequestExceptionParameters.Problem],
                    Advice = parameters.AdditionalParameters[OAuthRequestExceptionParameters.ProblemAdvice],
                    Source = OAuthRequestExceptionSources.Remote
                };

                // Load additional parameter for specific types
                switch (parameters.AdditionalParameters[OAuthRequestExceptionParameters.Problem])
                {
                    case OAuthRequestExceptionProblemTypes.VersionRejected:
                        if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableVersions]))
                            ex.AdditionalParameter = new KeyValuePair<string, string>(
                                OAuthRequestExceptionParameters.AcceptableVersions,
                                parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableVersions]);

                        break;

                    case OAuthRequestExceptionProblemTypes.ParameterAbsent:
                        if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersAbsent]))
                            ex.AdditionalParameter = new KeyValuePair<string, string>(
                                OAuthRequestExceptionParameters.ParametersAbsent,
                                parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersAbsent]);

                        break;

                    case OAuthRequestExceptionProblemTypes.ParameterRejected:
                        if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersRejected]))
                            ex.AdditionalParameter = new KeyValuePair<string, string>(
                                OAuthRequestExceptionParameters.ParametersRejected,
                                parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersRejected]);

                        break;

                    case OAuthRequestExceptionProblemTypes.TimestampRefused:
                        if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableTimestamps]))
                            ex.AdditionalParameter = new KeyValuePair<string, string>(
                                OAuthRequestExceptionParameters.AcceptableTimestamps,
                                parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableTimestamps]);

                        break;
                }

                // Throw the OAuthRequestException
                throw ex;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// 作者:Vincen
        /// 时间:2013.11.18 AM
        /// 描述:获取MC访问密钥(Token)
        /// </summary>
        /// <param name="type">用户类型(1:教师 2:学员 3:管理员)</param>
        /// <param name="userId">用户编号</param>
        /// <param name="userName">用户名称(一般为英文名)</param>
        /// <returns></returns>
        public static string GetMcToken(string type, string userId, string userName)
        {
            IConsumer fixedConsumer = new OAuthConsumer(WebCommon.Global.McKey, WebCommon.Global.McSecret, "METEN", ConsumerStatus.Valid);

            var timestamp = UnixTime.ToUnixTime(DateTime.Now);
            var uri = new Uri(WebCommon.Global.McAuthenticateUrl);

            var parameters = new OAuthParameters()
            {
                ConsumerKey = fixedConsumer.Key,
                Nonce = new GuidNonceProvider().GenerateNonce(timestamp),
                SignatureMethod = "HMAC-SHA1",
                Timestamp = timestamp.ToString(CultureInfo.InvariantCulture),
                Version = "1.0"
            };

            //--自定义参数
            parameters.AdditionalParameters.Add("user", userId);
            parameters.AdditionalParameters.Add("username", userName);
            switch (type)
            {
                case "1"://教师
                    parameters.AdditionalParameters.Add("teacher", "true");
                    break;
                case "2"://学员
                    break;
                case "3"://管理员
                    parameters.AdditionalParameters.Add("admin", "true");
                    break;
            }
            //--自定义参数

            //parameters.Signature = ServiceProviderContext.GetSigningProvider("HMAC-SHA1").ComputeSignature(SignatureBase.Create("GET", uri, parameters), fixedConsumer.Secret, null);

            var builder = new UriBuilder(uri)
            {
                Query = parameters.ToQueryStringFormat()
            };

            var token = string.Empty;
            var webRequest = WebRequest.Create(builder.Uri) as HttpWebRequest;
            if (null != webRequest)
            {
                webRequest.ServicePoint.Expect100Continue = false;

                using (var stream = webRequest.GetResponse().GetResponseStream())
                {
                    if (null != stream)
                    {
                        using (var responseReader = new StreamReader(stream))
                        {
                            var responseData = responseReader.ReadToEnd();
                            XDocument xdoc = XDocument.Parse(responseData);
                            var query = from n in xdoc.Descendants("token") select n;
                            token = query.First().Value;
                        }
                    }
                }
            }

            return token;
        }
Exemplo n.º 31
0
        public Uri BuildEchoCallUri(params KeyValuePair<string, string>[] pairs)
        {
            int timestamp = UnixTime.ToUnixTime(DateTime.Now);

            OAuthParameters parameters = new OAuthParameters();
            parameters.ConsumerKey = ConsumerStore.FixedConsumer.Key;
            parameters.Nonce = new GuidNonceProvider().GenerateNonce(timestamp);
            parameters.SignatureMethod = "HMAC-SHA1";
            parameters.Timestamp = timestamp.ToString(CultureInfo.InvariantCulture);
            parameters.Version = "1.0";
            parameters.Token = TokenGenerator.FixedAccessToken.Token;

            foreach (KeyValuePair<string, string> pair in pairs)
                parameters.AdditionalParameters.Add(pair.Key, pair.Value);

            parameters.Signature = ServiceProviderContext.GetSigningProvider("HMAC-SHA1").ComputeSignature(
                SignatureBase.Create("GET", this.EchoApiBaseUri, parameters),
                ConsumerStore.FixedConsumer.Secret,
                TokenGenerator.FixedAccessToken.Secret);

            UriBuilder builder = new UriBuilder(this.EchoApiBaseUri)
            {
                Query = parameters.ToQueryStringFormat()
            };

            return builder.Uri;
        }
Exemplo n.º 32
0
        private OAuthParameters ToParameters(Request request, CredentialSet credentials)
        {
            var options = Options.Default;

            var parameters = new OAuthParameters {
                ConsumerKey     = credentials.Consumer.Key,
                Timestamp       = NewTimestamp,
                Nonce           = NewNonce,
                SignatureMethod = options.SignatureMethod,
                Version         = options.Version.ToString()
            };

            parameters.AdditionalParameters.Add(CollectAllParameters(request));

            un.less(String.IsNullOrEmpty(credentials.Token.Key), () =>
                parameters.Token = credentials.Token.Key
            );

            return parameters;
        }
Exemplo n.º 33
0
 /// <summary>
 /// Parses the OAuth parameters from the HTTP request, sourcing
 /// parameters from all 3 of:
 /// <list>
 ///   <item>The HTTP Authorization header, if present</item>
 ///   <item>The POST body, if present and if the content-type is
 ///         <c>application/x-www-form-urlencoded</c></item>
 ///   <item>The query string, if present</item>
 /// </list>
 /// TODO: Mention validation
 /// </summary>
 ///
 /// <param name="request">The HTTP request</param>
 ///
 /// <returns>
 /// An OAuthParameters object containing the parsed reserved OAuth
 /// parameters and any additional, valid parameters
 /// </returns>
 public static OAuthParameters Parse(HttpRequest request)
 {
     return(OAuthParameters.Parse(request, OAuthParameterSources.ServiceProviderDefault));
 }
Exemplo n.º 34
0
        public Uri BuildAuthorizationUrl(
            IToken token,             
            NameValueCollection additionalParameters)
        {
            if (token.Type == TokenType.Request)
            {                
                OAuthParameters authParameters = new OAuthParameters()
                {
                    Token = token.Token
                };                

                if (additionalParameters != null)
                    authParameters.AdditionalParameters.Add(additionalParameters);

                // Construct final authorization Uri (HTTP method must be GET)
                string query = authParameters.ToQueryStringFormat();

                UriBuilder authUri = new UriBuilder(this.AuthorizationUrl);

                if (String.IsNullOrEmpty(authUri.Query))
                    authUri.Query = query;
                else
                    authUri.Query = authUri.Query.Substring(1) + "&" + query;

                return authUri.Uri;
            }
            else
                throw new ArgumentException("Invalid token type for Authorization");
        }
Exemplo n.º 35
0
 /// <summary>
 /// Parses the OAuth parameters from the HTTP request, sourcing
 /// parameters from the sources specified by <paramref name="sources"/>.
 ///
 /// TODO: Mention validation
 /// </summary>
 ///
 /// <param name="request">The HTTP request</param>
 /// <param name="sources">The sources to collate parameters from
 /// (must not be <c>OAuthParameterSources.None</c>)</param>
 ///
 /// <returns>
 /// An OAuthParameters object containing the parsed reserved OAuth
 /// parameters and any additional, valid parameters
 /// </returns>
 public static OAuthParameters Parse(HttpRequest request, OAuthParameterSources sources)
 {
     return(OAuthParameters.DoParse(request.Headers[Constants.AuthorizationHeaderParameter], request.Headers[Constants.WwwAuthenticateHeaderParameter], request.Form, request.QueryString, sources, true));
 }
        public void TestConsumerRequestSignature()
        {
            OAuthService service = OAuthService.Create(
               new EndPoint("http://example.com/request_token"),
               new Uri("http://example.com/authorize"),
               new EndPoint("http://example.com/access_token"),
               new MockConsumer()
               {
                   Key = "dpf43f3p2l4k3l03",
                   Secret = "kd94hf93k423kf44",
                   Status = ConsumerStatus.Valid
               });

            OAuthRequest consumerRequest = 
                OAuthConsumerRequest.Create( 
                new EndPoint("http://provider.example.net/profile", "GET"),
                service);

            OAuthParameters authParameters = new OAuthParameters()
            {
                ConsumerKey = service.Consumer.Key,
                Realm = service.Realm,
                SignatureMethod = service.SignatureMethod,
                Timestamp = "1191242096",
                Nonce = "kllo9940pd9333jh",
                Version = service.OAuthVersion
            };

            Assert.AreEqual(
                SignatureBase.Create(consumerRequest.ResourceEndPoint.HttpMethod, consumerRequest.ResourceEndPoint.Uri, authParameters),
                "GET&http%3A%2F%2Fprovider.example.net%2Fprofile&oauth_consumer_key%3Ddpf43f3p2l4k3l03%26oauth_nonce%3Dkllo9940pd9333jh%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1191242096%26oauth_version%3D1.0");

            authParameters.Sign(consumerRequest.ResourceEndPoint.Uri,
                                    consumerRequest.ResourceEndPoint.HttpMethod,
                                    service.Consumer,
                                    consumerRequest.RequestToken,
                                    new OAuth.Net.Components.HmacSha1SigningProvider());

            Assert.AreEqual( authParameters.Signature, "SGtGiOrgTGF5Dd4RUMguopweOSU=");

        }
Exemplo n.º 37
0
        //// TODO: ThrowAdditionalAuthorizationRequired
        //// TODO: ThrowPermissionUnknown
        //// TODO: ThrowPermissionDenied
        //// TODO: ThrowUserRefused

        /// <summary>
        /// Tries to parse an OAuthRequestException from some OAuth parameters. If an exception
        /// is indicated, the exception will be re-thrown.
        /// </summary>
        ///
        /// <remarks>
        /// <para>
        /// If no exception is indicated, this method will return without throwing.
        /// </para>
        ///
        /// <para>
        /// This will handle future <a href="http://wiki.oauth.net/ProblemReporting">Problem
        /// Reporting</a> problem types, but not future additional parameters.
        /// </para>
        /// </remarks>
        ///
        /// <example>
        /// This example shows how to rethrow an OAuth exception transmitted in a HTTP response.
        ///
        /// <code lang="C#" numberLines="true">
        /// HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        /// OAuthParameters responseParameters = OAuthParameters.Parse(response);
        /// OAuthRequestException.TryRethrow(responseParameters);
        /// </code>
        /// </example>
        ///
        /// <param name="parameters">The OAuth parameters</param>
        ///
        /// <exception cref="OAuth.Net.Common.OAuthRequestException">
        /// If the OAuth parameters indicate an OAuth exception
        /// </exception>
        public static void TryRethrow(OAuthParameters parameters)
        {
            if (parameters == null || parameters.AdditionalParameters == null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.Problem]))
            {
                OAuthRequestException ex = new OAuthRequestException()
                {
                    Problem = parameters.AdditionalParameters[OAuthRequestExceptionParameters.Problem],
                    Advice  = parameters.AdditionalParameters[OAuthRequestExceptionParameters.ProblemAdvice],
                    Source  = OAuthRequestExceptionSources.Remote
                };

                // Load additional parameter for specific types
                switch (parameters.AdditionalParameters[OAuthRequestExceptionParameters.Problem])
                {
                case OAuthRequestExceptionProblemTypes.VersionRejected:
                    if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableVersions]))
                    {
                        ex.AdditionalParameter = new KeyValuePair <string, string>(
                            OAuthRequestExceptionParameters.AcceptableVersions,
                            parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableVersions]);
                    }

                    break;

                case OAuthRequestExceptionProblemTypes.ParameterAbsent:
                    if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersAbsent]))
                    {
                        ex.AdditionalParameter = new KeyValuePair <string, string>(
                            OAuthRequestExceptionParameters.ParametersAbsent,
                            parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersAbsent]);
                    }

                    break;

                case OAuthRequestExceptionProblemTypes.ParameterRejected:
                    if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersRejected]))
                    {
                        ex.AdditionalParameter = new KeyValuePair <string, string>(
                            OAuthRequestExceptionParameters.ParametersRejected,
                            parameters.AdditionalParameters[OAuthRequestExceptionParameters.ParametersRejected]);
                    }

                    break;

                case OAuthRequestExceptionProblemTypes.TimestampRefused:
                    if (!string.IsNullOrEmpty(parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableTimestamps]))
                    {
                        ex.AdditionalParameter = new KeyValuePair <string, string>(
                            OAuthRequestExceptionParameters.AcceptableTimestamps,
                            parameters.AdditionalParameters[OAuthRequestExceptionParameters.AcceptableTimestamps]);
                    }

                    break;
                }

                // Throw the OAuthRequestException
                throw ex;
            }
        }