public void ShouldReturnChallengeOnEmptyAuthHeaderWithStatusUnauthorized()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(HttpStatusCode.Unauthorized), (id) =>
            {
                return(Task.FromResult(new HawkCredential
                {
                    Id = "123",
                    Algorithm = "sha1",
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    User = "******"
                }));
            });

            var invoker = new HttpMessageInvoker(handler);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Host = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.IsTrue(response.Headers.WwwAuthenticate.Any(h => h.Scheme == "Hawk"));
        }
        public void ShouldGenerateServerAuthHeader()
        {
            var credential = new HawkCredential
            {
                Id        = "123",
                Algorithm = "sha1",
                Key       = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                User      = "******"
            };

            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) =>
            {
                return(Task.FromResult(credential));
            }, 60, true);

            var invoker = new HttpMessageInvoker(handler);

            var ts  = Hawk.ConvertToUnixTimestamp(DateTime.Now);
            var mac = Hawk.CalculateMac("example.com", "get", new Uri("http://example.com:8080/resource/4?filter=a"), "hello", ts.ToString(), "j4h3g2", credential, "header");

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", string.Format("id = \"456\", ts = \"{0}\", nonce=\"j4h3g2\", mac = \"{1}\", ext = \"hello\"",
                                                                                                ts, mac));

            request.Headers.Host = "example.com";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.IsTrue(response.Headers.Any(h => h.Key == "Server-Authorization"));
        }
        public void ShouldFailOnInvalidCredentials()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) =>
            {
                return(Task.FromResult(new HawkCredential
                {
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    User = "******"
                }));
            });

            var invoker = new HttpMessageInvoker(handler);

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\"");
            request.Headers.Host          = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.AreEqual("Invalid credentials", response.ReasonPhrase);
        }
        public void ShouldFailOnUnknownBadMac()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) =>
            {
                return(Task.FromResult(new HawkCredential
                {
                    Id = "123",
                    Algorithm = "sha256",
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    User = "******"
                }));
            });

            var invoker = new HttpMessageInvoker(handler);

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"/qwS4UjfVWMcU4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\"");
            request.Headers.Host          = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.AreEqual("Bad mac", response.ReasonPhrase);
        }
        public void ShouldParseValidAuthHeaderWithSha256()
        {
            var credential = new HawkCredential
            {
                Id        = "123",
                Algorithm = "hmacsha256",
                Key       = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                User      = "******"
            };

            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) =>
            {
                return(credential);
            });

            var invoker = new HttpMessageInvoker(handler);

            var ts  = Math.Floor(Hawk.ConvertToUnixTimestamp(DateTime.Now) / 1000);
            var mac = Hawk.CalculateMac("example.com", "get", new Uri("http://example.com:8080/resource/4?filter=a"), "hello", ts.ToString(), "j4h3g2", credential, "header");

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", string.Format("id = \"456\", ts = \"{0}\", nonce=\"j4h3g2\", mac = \"{1}\", ext = \"hello\"",
                                                                                                ts, mac));

            request.Headers.Host = "example.com";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.AreEqual(Thread.CurrentPrincipal.GetType(), typeof(ClaimsPrincipal));
        }
示例#6
0
        private static void Main()
        {
            const string address = "http://localhost:925/";

            var config = new HttpSelfHostConfiguration(address);

            config.MapHttpAttributeRoutes();
            var handler = new HawkMessageHandler(
                async id => new HawkCredential
            {
                Id        = id,
                Key       = "abcdefghijkl",
                Algorithm = "sha256",
                User      = "******"
            }, 4, true);

            config.MessageHandlers.Add(handler);

            using (var server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                var client = new HttpClient();

                //this will fail
                var request  = new HttpRequestMessage(HttpMethod.Get, address + "test");
                var response = client.SendAsync(request).Result;
                Console.WriteLine(response.StatusCode);
                Console.WriteLine();

                var credential = new HawkCredential
                {
                    Id        = "this-is-my-id",
                    Key       = "abcdefghijkl",
                    Algorithm = "sha256",
                    User      = "******"
                };

                var clientHandler = new HawkClientMessageHandler(new HttpClientHandler(), credential, ts: DateTime.Now);
                var client2       = new HttpClient(clientHandler);

                //this will succeed
                request = new HttpRequestMessage(HttpMethod.Get, address + "test");
                var response2 = client2.SendAsync(request).Result;
                Console.WriteLine(response2.StatusCode);
                Console.WriteLine(response2.Content.ReadAsStringAsync().Result);
                Console.WriteLine();

                Console.WriteLine("Sleeping to get outside of the timestamp window. Next request will fail - replay protection.");
                Thread.Sleep(5000);

                //this will fail
                request = new HttpRequestMessage(HttpMethod.Get, address + "test");
                var response3 = client2.SendAsync(request).Result;
                Console.WriteLine(response3.StatusCode);
                Console.WriteLine();

                Console.ReadLine();
            }
        }
        public void ShouldFailOnWMissingHostHeader()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), GetCredential);
            var invoker = new HttpMessageInvoker(handler);

            var request = new HttpRequestMessage();

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"123\", ts = \"1353788437\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\"");

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.AreEqual("Missing Host header", response.ReasonPhrase);
        }
        public void ShouldSkipAuthOnWrongAuthScheme()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), GetCredential);
            var invoker = new HttpMessageInvoker(handler);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Basic");

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.IsNotNull(response);
            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
        }
        public void ShouldFailOnInvalidAuthFormat()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), GetCredential);
            var invoker = new HttpMessageInvoker(handler);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "");
            request.Headers.Host          = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);
            Assert.AreEqual("Invalid header format", response.ReasonPhrase);
        }
        public void ShouldFailOnUnknownAuthAttribute()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), GetCredential);
            var invoker = new HttpMessageInvoker(handler);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"123\", ts = \"1353788437\", nonce = \"1353788437\", x = \"3\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\"");
            request.Headers.Host          = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.AreEqual("Unknown attributes", response.ReasonPhrase);
        }
        public void ShouldFailOnMissingCredentials()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) => { return(null); });
            var invoker = new HttpMessageInvoker(handler);

            var ts = Math.Floor(Hawk.ConvertToUnixTimestamp(DateTime.Now) / 1000).ToString();

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\"");
            request.Headers.Host          = "localhost";

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.AreEqual("Missing credentials", response.ReasonPhrase);
        }
        public void ShouldFailOnCredentialsFuncException()
        {
            var handler = new HawkMessageHandler(new DummyHttpMessageHandler(), (id) => { throw new Exception("Invalid"); });
            var invoker = new HttpMessageInvoker(handler);

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com:8080/resource/4?filter=a");

            request.Headers.Authorization = new AuthenticationHeaderValue("Hawk", "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\"");
            request.Headers.Host          = "localhost";
            request.Content = new StringContent("foo");
            request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

            var response = invoker.SendAsync(request, new CancellationToken())
                           .Result;

            Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode);
            Assert.AreEqual("Unknown user", response.ReasonPhrase);
        }
示例#13
0
        public static void Register(HttpConfiguration config)
        {
            var handler = new HawkMessageHandler(new HttpControllerDispatcher(config),
                                                 (id) =>
            {
                return(Task.FromResult(new HawkCredential
                {
                    Id = "dh37fgj492je",
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    Algorithm = "sha256",
                    User = "******"
                }));
            }, 60, true);

            config.Routes.MapHttpRoute(
                "DefaultApi",
                "api/{controller}/{id}",
                new { id = RouteParameter.Optional },
                null,
                handler
                );
        }
示例#14
0
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            var handler = new HawkMessageHandler(new HttpControllerDispatcher(config),
                                                 (id) =>
            {
                return(Task.FromResult(new HawkCredential
                {
                    Id = id,
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    Algorithm = "sha256",
                    User = "******"
                }));
            });

            config.Routes.MapHttpRoute(
                "Filter", "api/filter",
                new
            {
                controller = "HelloWorldWithFilter"
            });

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new
            {
                id         = RouteParameter.Optional,
                controller = "HelloWorld"
            },
                null,
                handler
                );

            appBuilder.UseWebApi(config);
        }
示例#15
0
        static void Main(string[] args)
        {
            var config = new HttpSelfHostConfiguration("http://localhost:8091");
            //config.Filters.Add(new RequiresHawkAttribute(typeof(HawkRepository)));

            var handler = new HawkMessageHandler(new HttpControllerDispatcher(config),
                                                 (id) =>
            {
                return(new HawkCredential
                {
                    Id = id,
                    Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    Algorithm = "hmacsha256",
                    User = "******"
                });
            });

            config.Routes.MapHttpRoute(
                "Filter", "api/filter",
                new
            {
                controller = "HelloWorldWithFilter"
            });

            config.Routes.MapHttpRoute(
                "API Default", "api/{controller}/{id}",
                new
            {
                id         = RouteParameter.Optional,
                controller = "HelloWorld"
            },
                null,
                handler
                );

            using (HttpSelfHostServer server = new HttpSelfHostServer(config))
            {
                server.OpenAsync().Wait();
                Console.WriteLine("Press Enter to quit.");

                var credential = new HawkCredential
                {
                    Id        = "dh37fgj492je",
                    Key       = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                    Algorithm = "hmacsha256",
                    User      = "******"
                };

                var clientHandler = new HawkClientMessageHandler(new HttpClientHandler(), credential, "some-app-data");
                var client        = new HttpClient(clientHandler);

                var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8091/Api/HelloWorld");
                request.Headers.Host = "localhost";

                var    response = client.SendAsync(request).Result;
                string message  = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Response {0} - Http Status Code {1}", message, response.StatusCode);

                var client2 = new HttpClient();

                request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8091/Api/HelloWorldAnonymous");
                request.Headers.Host = "localhost";

                response = client2.SendAsync(request).Result;
                message  = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Response {0} - Http Status Code {1}", message, response.StatusCode);

                var client3 = new HttpClient();

                var bewit = Hawk.GetBewit("localhost", new Uri("http://localhost:8091/Api/HelloWorld"), credential, 60000);

                request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8091/Api/HelloWorld?bewit=" + bewit);
                request.Headers.Host = "localhost";

                response = client3.SendAsync(request).Result;

                message = response.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Response {0} - Http Status Code {1}", message, response.StatusCode);

                var client4 = new HttpClient(clientHandler);

                var request4 = new HttpRequestMessage(HttpMethod.Get, "http://localhost:8091/api/filter");
                request4.Headers.Host = "localhost";

                var    response4 = client4.SendAsync(request4).Result;
                string message4  = response4.Content.ReadAsStringAsync().Result;
                Console.WriteLine("Response {0} - Http Status Code {1}", message4, response4.StatusCode);

                Console.WriteLine("Press a key to close the app");
                Console.ReadLine();
            }
        }