Exemplo n.º 1
0
        // helper extension method to sign each JSON request with OAuth
        public static void SetAccessToken(this JsonServiceClient client, IToken access_token)
        {
            // we use a request filter to add the required OAuth header
            client.LocalHttpWebRequestFilter += webservice_request => {

                OAuthConsumerContext consumer_context = new OAuthConsumerContext ();

                consumer_context.SignatureMethod = "HMAC-SHA1";
                consumer_context.ConsumerKey = access_token.ConsumerKey;
                consumer_context.ConsumerSecret = "anyone";
                consumer_context.UseHeaderForOAuthParameters = true;

                // the OAuth process creates a signature, which uses several data from
                // the web request like method, hostname, headers etc.
                OAuthContext request_context = new OAuthContext ();
                request_context.Headers = webservice_request.Headers;
                request_context.RequestMethod = webservice_request.Method;
                request_context.RawUri = webservice_request.RequestUri;

                // now create the signature for that context
                consumer_context.SignContextWithToken (request_context, access_token);

                // BUG TODO the oauth_token is not included when generating the header,
                // this is a bug ing DevDefined.OAuth. We add it manually as a workaround
                request_context.AuthorizationHeaderParameters.Add ("oauth_token", access_token.Token);

                string oauth_header = request_context.GenerateOAuthParametersForHeader ();

                webservice_request.Headers.Add ("Authorization", oauth_header);

            };
        }
		public IOAuthContext FromHttpRequest(HttpRequestBase request)
		{
			var context = new OAuthContext
			              	{
			              		RawUri = CleanUri(request.Url),
			              		Cookies = CollectCookies(request),
			              		Headers = GetCleanedNameValueCollection(request.Headers),
			              		RequestMethod = request.HttpMethod,
			              		FormEncodedParameters = GetCleanedNameValueCollection(request.Form),
			              		QueryParameters = GetCleanedNameValueCollection(request.QueryString),
			              	};

            if (request.InputStream.Length > 0)
            {
                context.RawContent = new byte[request.InputStream.Length];
                request.InputStream.Read(context.RawContent, 0, context.RawContent.Length);
                request.InputStream.Position = 0;
            }

			if (request.Headers.AllKeys.Contains("Authorization"))
			{
				context.AuthorizationHeaderParameters = UriUtility.GetHeaderParameters(request.Headers["Authorization"]).ToNameValueCollection();
				context.UseAuthorizationHeader = true;
			}

			return context;
		}
    public void AuthenticationPasses()
    {
      var context = new OAuthContext { XAuthMode = "client_auth", XAuthUsername = "******", XAuthPassword = "******" };

      var inspector = new XAuthValidationInspector(ValidateXAuthMode, this.AuthenticateXAuthUsernameAndPassword);
      Assert.DoesNotThrow(() => inspector.InspectContext(ProviderPhase.CreateAccessToken, context));
    }
Exemplo n.º 4
0
        public void it_can_parse_valid_IfModifiedSince_date()
        {
            var consumerRequest = NewConsumerRequest();
            var headers = new NameValueCollection { { "If-Modified-Since", "2012-04-01 23:45:00" } };
            var oauthContext = new OAuthContext { Headers = headers };

            Assert.AreEqual(new DateTime(2012, 04, 01, 23, 45, 0), consumerRequest.ParseIfModifiedSince(oauthContext));
        }
Exemplo n.º 5
0
        public void it_can_parse_null_IfModifiedSince_date()
        {
            var consumerRequest = NewConsumerRequest();
            var headers = new NameValueCollection { { "If-Modified-Since", null } };
            var oauthContext = new OAuthContext { Headers = headers };

            Assert.AreEqual(null, consumerRequest.ParseIfModifiedSince(oauthContext));
        }
Exemplo n.º 6
0
        public void it_can_parse_unset_IfModifiedSince_date()
        {
            ConsumerRequest consumerRequest = new ConsumerRequest(null, null, null, null);
            NameValueCollection headers = new NameValueCollection();
            OAuthContext oauthContext = new OAuthContext {Headers = headers};

            Assert.AreEqual(null, consumerRequest.ParseIfModifiedSince(oauthContext));
        }
    public void InvalidModeThrows()
    {
      var context = new OAuthContext { XAuthMode = "test_mode" };

      var inspector = new XAuthValidationInspector(ValidateXAuthMode, this.AuthenticateXAuthUsernameAndPassword);
      var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.CreateAccessToken, context));
      Assert.Equal("The x_auth_mode parameter is invalid", ex.Message);
    }
    public void EmptyPasswordThrows()
    {
      var context = new OAuthContext { XAuthMode = "client_auth", XAuthUsername = "******" };

      var inspector = new XAuthValidationInspector(ValidateXAuthMode, this.AuthenticateXAuthUsernameAndPassword);
      var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.CreateAccessToken, context));
      Assert.Equal("The x_auth_password parameter must be present", ex.Message);
    }
    public void AuthenticationFailureThrows()
    {
      var context = new OAuthContext { XAuthMode = "client_auth", XAuthUsername = "******", XAuthPassword = "******" };

      var inspector = new XAuthValidationInspector(ValidateXAuthMode, this.AuthenticateXAuthUsernameAndPassword);
      var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.CreateAccessToken, context));
      Assert.Equal("Authentication failed with the specified username and password", ex.Message);
    }
		public void inspect_body_for_plainttext_signature_does_nothing()
		{
			var context = new OAuthContext
			              	{
			              		UseAuthorizationHeader = true,
			              		BodyHash = "wrong",
			              		SignatureMethod = SignatureMethod.PlainText
			              	};

			Assert.DoesNotThrow(() => inspector.InspectContext(ProviderPhase.AccessProtectedResourceRequest, context));
		}
		public void inspect_body_for_hmac_sha1_signature_does_not_throw_when_hash_matches()
		{
			var context = new OAuthContext
			              	{
			              		UseAuthorizationHeader = true,
			              		BodyHash = EmptyBodyHash,
			              		SignatureMethod = SignatureMethod.HmacSha1
			              	};

			Assert.DoesNotThrow(() => inspector.InspectContext(ProviderPhase.AccessProtectedResourceRequest, context));
		}
    public void WithAfterRange()
    {
      var inspector = new TimestampRangeInspector(new TimeSpan(0, 0, 0), new TimeSpan(1, 0, 0),
                                                  () => new DateTime(2008, 1, 1, 12, 0, 0));

      var context = new OAuthContext
        {
          Timestamp = new DateTime(2008, 1, 1, 13, 0, 0).Epoch().ToString()
        };

      inspector.InspectContext(ProviderPhase.GrantRequestToken, context);
    }
    public void InspectContextForUniqueNoncePasses()
    {
      var nonceStore = MockRepository.GenerateStub<INonceStore>();

      var context = new OAuthContext {Nonce = "2"};

			nonceStore.Stub(stub=>stub.RecordNonceAndCheckIsUnique(context, "2")).Return(true);
      
			var inspector = new NonceStoreInspector(nonceStore);

    	Assert.DoesNotThrow(() => inspector.InspectContext(ProviderPhase.GrantRequestToken, context));      
    }
		public void inspect_body_for_hmac_sha1_signature_throws_when_hash_does_not_match()
		{
			var context = new OAuthContext
			              	{
			              		UseAuthorizationHeader = true,
			              		BodyHash = "wrong",
			              		SignatureMethod = SignatureMethod.HmacSha1
			              	};

			var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.AccessProtectedResourceRequest, context));

			Assert.Equal("Failed to validate body hash", ex.Message);
		}
		public void InValidConsumerThrows()
		{
			var consumerStore = MockRepository.GenerateStub<IConsumerStore>();

			var context = new OAuthContext {ConsumerKey = "key"};

			consumerStore.Stub(stub => stub.IsConsumer(context)).Return(false);

			var inspector = new OAuth.Provider.Inspectors.ConsumerValidationInspector(consumerStore);

			var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.GrantRequestToken, context));

			Assert.Equal("Unknown Consumer (Realm: , Key: key)", ex.Message);
		}
    public void OutsideBeforeRange()
    {
      var inspector = new TimestampRangeInspector(new TimeSpan(1, 0, 0), new TimeSpan(0, 0, 0),
                                                  () => new DateTime(2008, 1, 1, 12, 0, 0));

      var context = new OAuthContext
        {
          Timestamp = new DateTime(2008, 1, 1, 10, 59, 59).Epoch().ToString()
        };

    	var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.GrantRequestToken, context));

			Assert.Equal("The timestamp is to old, it must be at most 3600 seconds before the servers current date and time", ex.Message);
    }
    public void InspectContextForRepeatedNonceThrows()
    {
      var nonceStore = MockRepository.GenerateStub<INonceStore>();

      var context = new OAuthContext {Nonce = "1"};

    	nonceStore.Stub(stub => stub.RecordNonceAndCheckIsUnique(context, "1")).Return(false);
			
			var inspector = new NonceStoreInspector(nonceStore);

    	var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.GrantRequestToken, context));

			Assert.Equal("The nonce value \"1\" has already been used", ex.Message);
    }
Exemplo n.º 18
0
        public void to_consumer_response_with_current_date_string_should_pass_validation()
        {
            const string recentDateString = "2012-04-01T00:00:00";

            var oAuthContext = new OAuthContext
            {
                RequestMethod = "GET",
                RawUri = new Uri("http://any.uri/"),
                Headers = new WebHeaderCollection { { "If-Modified-Since", recentDateString } }
            };

            var consumerRequest = NewConsumerRequest(oAuthContext);

            Assert.DoesNotThrow(() => consumerRequest.ToWebRequest());
        }
    public void InspectContextForUniqueNoncePasses()
    {
      var repository = new MockRepository();

      var nonceStore = repository.StrictMock<INonceStore>();
      var context = new OAuthContext {Nonce = "2"};

      using (repository.Record())
      {
        Expect.Call(nonceStore.RecordNonceAndCheckIsUnique(context, "2")).Return(true);
      }
      using (repository.Playback())
      {
        var inspector = new NonceStoreInspector(nonceStore);
        inspector.InspectContext(ProviderPhase.GrantRequestToken, context);
      }
    }
    public void ValidConsumerPassesThrough()
    {
      var repository = new MockRepository();

      var consumerStore = repository.StrictMock<IConsumerStore>();
      var context = new OAuthContext {ConsumerKey = "key"};

      using (repository.Record())
      {
        Expect.Call(consumerStore.IsConsumer(context)).Return(true);
      }
      using (repository.Playback())
      {
        var inspector = new OAuth.Provider.Inspectors.ConsumerValidationInspector(consumerStore);
        inspector.InspectContext(ProviderPhase.GrantRequestToken, context);
      }
    }
Exemplo n.º 21
0
        public void to_consumer_response_with_really_old_date_string_should_fail_validation()
        {
            const string reallyOldDateString = "1000-01-01T00:00:00";

            var oAuthContext = new OAuthContext
            {
                RequestMethod = "GET", 
                RawUri = new Uri("http://any.uri/"),
                Headers = new WebHeaderCollection { { "If-Modified-Since", reallyOldDateString } }
            };

            var consumerRequest = NewConsumerRequest(oAuthContext);

            var ex = Assert.Throws<ArgumentOutOfRangeException>(() => consumerRequest.ToWebRequest());

            const string expectedMessage = "Supplied value of If-Modified-Since header is too small";
            Assert.IsTrue(ex.Message.Contains(expectedMessage), string.Format("Exception message <{0}> is not as expected <{1}>", ex.Message, expectedMessage));
        }
Exemplo n.º 22
0
        public void TestSignRequestToken()
        {
            var cert = new X509Certificate2("XeroApiNet-Sample.pfx", "password");

            var consumerContext = new OAuthConsumerContext
            {
                // Partner and Private apps use RSA-SHA1 signing method
                SignatureMethod = SignatureMethod.RsaSha1,
                UseHeaderForOAuthParameters = true,

                // Urls
                RequestTokenUri = null,
                UserAuthorizeUri = null,
                AccessTokenUri = XeroApiEndpoints.PublicAccessTokenUri,
                BaseEndpointUri = XeroApiEndpoints.PublicBaseEndpointUri,

                Key = cert.PrivateKey,
                ConsumerKey = ConsumerKey,
                ConsumerSecret = string.Empty,
                UserAgent = UserAgent,
            };

            var oauthContext = new OAuthContext
            {
                RequestMethod = "POST",
                RawUri = new Uri("https://photos.example.net/request_token"),
                ConsumerKey = "dpf43f3p2l4k3l03",
                SignatureMethod = SignatureMethod.RsaSha1,
                Timestamp = "1191242090",
                Nonce = "hsu94j3884jdopsl",
                Version = "1.0"
            };

            var signatureBase = oauthContext.GenerateSignatureBase();
            consumerContext.Signer.SignContext(oauthContext,
                                               new SigningContext
                                               {
                                                   Algorithm = consumerContext.Key,
                                                   ConsumerSecret = null,
                                                   SignatureBase = signatureBase
                                               });

            Assert.That(oauthContext.Signature, Is.EqualTo("aIIAFPjD0uavubFeL/Hz4LSV6NsvAbrvfnPF6OcgGfhML5ezO0+E+tofLgp1SHbLyNFM7D1p/SJN1J4MY7T3HzvM8HX+3u5Q+Ui+en0/ewHZ+3ar6BA7r3zOYqDn8rfCGSnweia3fFYmjkeS8NvKShnewUu0jUFbnG4RXw8BiEk="));
        }
    public void PlainTextSignatureMethodDoesNotFetchCertificate()
    {
      var repository = new MockRepository();

      var consumerStore = repository.DynamicMock<IConsumerStore>();
      var signer = repository.StrictMock<IOAuthContextSigner>();

      var context = new OAuthContext {ConsumerKey = "key", SignatureMethod = SignatureMethod.PlainText};

      using (repository.Record())
      {
        Expect.Call(signer.ValidateSignature(null, null)).IgnoreArguments().Return(true);
      }
      using (repository.Playback())
      {
        var inspector = new SignatureValidationInspector(consumerStore, signer);
        inspector.InspectContext(ProviderPhase.GrantRequestToken, context);
      }
    }
Exemplo n.º 24
0
		public void generate_signature_when_token_is_url_encoded()
		{
			var context = new OAuthContext
			              	{
			              		RequestMethod = "GET",
			              		RawUri = new Uri("https://www.google.com/m8/feeds/contacts/default/base"),
			              		Token = "1/2",
			              		ConsumerKey = "context",
			              		SignatureMethod = SignatureMethod.RsaSha1
			              	};

			Assert.Equal(
				"GET&https%3A%2F%2Fwww.google.com%2Fm8%2Ffeeds%2Fcontacts%2Fdefault%2Fbase&oauth_consumer_key%3Dcontext%26oauth_signature_method%3DRSA-SHA1%26oauth_token%3D1%252F2",
				context.GenerateSignatureBase());

			Assert.Equal(
				"https://www.google.com/m8/feeds/contacts/default/base?oauth_token=1%2F2&oauth_consumer_key=context&oauth_signature_method=RSA-SHA1",
				context.GenerateUrl());
		}
    public void InvalidSignatureThrows()
    {
      var repository = new MockRepository();

      var consumerStore = repository.DynamicMock<IConsumerStore>();
      var signer = repository.StrictMock<IOAuthContextSigner>();

      var context = new OAuthContext {ConsumerKey = "key", SignatureMethod = SignatureMethod.PlainText};

      using (repository.Record())
      {
        Expect.Call(signer.ValidateSignature(null, null)).IgnoreArguments().Return(false);
      }
      using (repository.Playback())
      {
        var inspector = new SignatureValidationInspector(consumerStore, signer);
      	var ex = Assert.Throws<OAuthException>(() => inspector.InspectContext(ProviderPhase.GrantRequestToken, context));
				Assert.Equal("Failed to validate signature", ex.Message);
      }
    }
    public IOAuthContext FromHttpRequest(HttpRequestBase request)
    {
        var context = new OAuthContext
        {
          RawUri = CleanUri(request.Url),
          Cookies = CollectCookies(request),
          Headers = new NameValueCollection(request.Headers),
          RequestMethod = request.HttpMethod,
          FormEncodedParameters = new NameValueCollection(request.Form),
          QueryParameters = new NameValueCollection(request.QueryString),
        };

        if (request.Headers.AllKeys.Contains("Authorization"))
        {
            context.AuthorizationHeaderParameters = UriUtility.GetHeaderParameters(request.Headers["Authorization"]).ToNameValueCollection();
            context.UseAuthorizationHeader = true;
        }

        return context;
    }
    public IOAuthContext FromMessage(Message request)
    {
        var requestProperty = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
        var context = new OAuthContext
        {
            RawUri = CleanUri(request.Headers.To),
            Headers = new NameValueCollection(requestProperty.Headers),
            RequestMethod = requestProperty.Method,
            QueryParameters = HttpUtility.ParseQueryString(requestProperty.QueryString),
        };

        string authHeader = requestProperty.Headers["Authorization"];
        if (!string.IsNullOrEmpty(authHeader))
        {
            context.AuthorizationHeaderParameters = UriUtility.GetHeaderParameters(authHeader).ToNameValueCollection();
            context.UseAuthorizationHeader = true;
        }

        return context;
    }
Exemplo n.º 28
0
        public IOAuthContext FromHttpRequest(HttpRequestBase request)
        {
            var context = new OAuthContext
                          	{
                          		RawUri = CleanUri(request.Url),
                          		Cookies = CollectCookies(request),
                          		Headers = GetCleanedNameValueCollection(request.Headers),
                          		RequestMethod = request.HttpMethod,
                          		FormEncodedParameters = GetCleanedNameValueCollection(request.Form),
                          		QueryParameters = GetCleanedNameValueCollection(request.QueryString),
                          	};

            if (request.InputStream.Length > 0)
            {
                context.RawContent = new byte[request.InputStream.Length];
                request.InputStream.Read(context.RawContent, 0, context.RawContent.Length);
                request.InputStream.Position = 0;
            }

            ParseAuthorizationHeader(request.Headers, context);

            return context;
        }
Exemplo n.º 29
0
		public void generate_signature_with_hello_world_body()
		{
			// generate a signature base, as per the oauth body hash spec example
			// http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html

			var context = new OAuthContext
			              	{
			              		RequestMethod = "POST",
			              		RawUri = new Uri("http://www.example.com/resource"),
			              		RawContentType = "text/plain",
			              		RawContent = Encoding.UTF8.GetBytes("Hello World!"),
			              		ConsumerKey = "consumer",
			              		SignatureMethod = "HMAC-SHA1",
			              		Timestamp = "1236874236",
			              		Version = "1.0",
			              		IncludeOAuthRequestBodyHashInSignature = true,
			              		Nonce = "10369470270925",
			              		Token = "token"
			              	};

			Assert.Equal(
				"POST&http%3A%2F%2Fwww.example.com%2Fresource&oauth_body_hash%3DLve95gjOVATpfV8EL5X4nxwjKHE%253D%26oauth_consumer_key%3Dconsumer%26oauth_nonce%3D10369470270925%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1236874236%26oauth_token%3Dtoken%26oauth_version%3D1.0",
				context.GenerateSignatureBase());
		}
Exemplo n.º 30
0
    public IConsumerRequest Request(IToken accessToken)
    {
      var context = new OAuthContext
        {
          UseAuthorizationHeader = ConsumerContext.UseHeaderForOAuthParameters
        };

      context.Cookies.Add(_cookies);
      context.FormEncodedParameters.Add(_formParameters);
      context.Headers.Add(_headers);
      context.QueryParameters.Add(_queryParameters);

      IConsumerRequest consumerRequest = _consumerRequestFactory.CreateConsumerRequest(context, ConsumerContext, accessToken);

      consumerRequest.ProxyServerUri = ProxyServerUri;
      consumerRequest.ResponseBodyAction = ResponseBodyAction;

      return consumerRequest;
    }
Exemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BoundParameter"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="context">The context.</param>
 public BoundParameter(string name, OAuthContext context)
 {
     _name    = name;
     _context = context;
 }