예제 #1
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            if (!request.Uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
            {
                var builder = new UriBuilder(request.Uri);
                builder.Scheme = "https";

                if (request.Uri.IsDefaultPort)
                {
                    builder.Port = -1;
                }

                response.Headers.Set("Location", builder.ToString());
                response.StatusCode = 302;

                return TaskAsyncHelper.Empty;
            }
            else
            {
                return _next(env);
            }
        }
        public void ShouldFailOnInvalidAuthFormat()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                ""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
                {
                    response.StatusCode = 401;
                    return Task.FromResult<object>(null);
                }),
               builder,
               new HawkAuthenticationOptions
               {
                   Credentials = GetCredential
               }
            );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Invalid header format", logger.Messages[0]);
        }
예제 #3
0
        public async static Task AppFunction(IDictionary<string, object> environment)
        {
            // process response
            var owinResponse = new OwinResponse(environment);
            var owinRequest = new OwinRequest(environment);
            var writer = new StreamWriter(owinResponse.Body);
            switch (owinRequest.Path)
            {
                case "/10mbTest.txt":
                    writer.Write(TestHelpers.FileContent10MbTest);
                    break;
                case "/simpleTest.txt":
                    writer.Write(TestHelpers.FileContentSimpleTest);
                    break;
                case "/emptyFile.txt":
                    writer.Write(TestHelpers.FileContentEmptyFile);
                    break;
                default:
                    writer.Write(TestHelpers.FileContentAnyFile);
                    break;
            }

            await writer.FlushAsync();

            owinResponse.ContentLength = owinResponse.Body.Length;
            owinResponse.ContentType = "text/plain";
        }
예제 #4
0
        public override async Task Invoke(IOwinContext context)
        {
            // process response
            var owinResponse = new OwinResponse(context.Environment) { ContentType = "text/plain" };
            var owinRequest = new OwinRequest(context.Environment);
            var writer = new StreamWriter(owinResponse.Body);
            switch (owinRequest.Path.Value)
            {
                case "/root/10mbTest.txt":
                    writer.Write(TestHelpers.FileContent5bTest);
                    owinResponse.ContentLength = TestHelpers.FileContent5bTest.Length;
                    break;
                case "/root/simpleTest.txt":
                    writer.Write(TestHelpers.FileContentSimpleTest);
                    owinResponse.ContentLength = TestHelpers.FileContentSimpleTest.Length;
                    break;
                case "/root/index.html":
                    writer.Write(TestHelpers.FileContentIndex);
                    owinResponse.ContentLength = TestHelpers.FileContentIndex.Length;
                    break;
                case "/root/emptyFile.txt":
                    writer.Write(TestHelpers.FileContentEmptyFile);
                    owinResponse.ContentLength = TestHelpers.FileContentEmptyFile.Length;
                    break;
                default:
                    writer.Write(TestHelpers.FileContentAnyFile);
                    owinResponse.ContentLength = TestHelpers.FileContentAnyFile.Length;
                    break;
            }

            await writer.FlushAsync();
        }
        /// <summary>
        /// Inspects the environment and checks to see if this is a POST containing the HTML form fields in the login.html page.
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="formsAuthenticationProvider"></param>
        public LoginContext(IDictionary<string, object> environment, FormsAuthenticationProvider formsAuthenticationProvider)
        {
            _environment = environment;
            Request = new OwinRequest(environment);
            Response = new OwinResponse(environment);

            _formsAuthenticationProvider = formsAuthenticationProvider;

            _responseStream = Response.Body;

            var requestContentType = Request.GetHeader("Content-Type");
            _isFormUrlEncodedPost = Request.Method == "POST" && !string.IsNullOrEmpty(requestContentType) && requestContentType.StartsWith("application/x-www-form-urlencoded");

            if (_isFormUrlEncodedPost && Request.Body != null)
            {
                _formData = Request.ReadForm().Result;

                var username = _formData["login_username"];
                var password = _formData["login_password"];
                var rememberMe = _formData["remember_me"] != null && _formData["remember_me"] == "yes";

                if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
                {
                    environment["formsauthn.username"] = username;
                    environment["formsauthn.password"] = password;
                    environment["formsauthn.remember"] = rememberMe;
                }
            }
        }
        public override Task ProcessRequest(HostContext context)
        {
            string alterWhen = "____Never____";
            int statusCode = 200;

            if (!String.IsNullOrEmpty(context.Request.QueryString["alterWhen"]))
            {
                alterWhen = context.Request.QueryString["alterWhen"];
            }

            if (!String.IsNullOrEmpty(context.Request.QueryString["statusCode"]))
            {
                statusCode = Int32.Parse(context.Request.QueryString["statusCode"]);
            }

            var owinRequest = new OwinRequest(context.Environment);

            if (owinRequest.Path.Value.Contains("/" + alterWhen))
            {
                var response = new OwinResponse(context.Environment);

                // Alter status code
                response.StatusCode = statusCode;

                using (var sw = new StreamWriter(response.Body))
                {
                    sw.WriteLine("Hello world");
                    sw.Flush();
                }

                return TaskAsyncHelper.Empty;
            }

            return base.ProcessRequest(context);
        }
예제 #7
0
        /// <summary>
        /// Create a new context with only request and response header collections.
        /// </summary>
        public OwinContext()
        {
            IDictionary <string, object> environment = new Dictionary <string, object>(StringComparer.Ordinal);

            environment[OwinConstants.RequestHeaders]  = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
            environment[OwinConstants.ResponseHeaders] = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
            Environment = environment;
            Request     = new OwinRequest(environment);
            Response    = new OwinResponse(environment);
        }
예제 #8
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            // The forms auth module has a bug where it null refs on a null Extra
            var headers = request.Get<IDictionary<string, string[]>>(Owin.Types.OwinConstants.RequestHeaders);

            var cookies = request.GetCookies();
            string cookieValue;
            if (cookies != null && cookies.TryGetValue("jabbr.id", out cookieValue))
            {
                AuthenticationTicket ticket = _ticketHandler.Unprotect(cookieValue);
                if (ticket != null && ticket.Extra == null)
                {
                    var extra = new AuthenticationExtra();
                    extra.IsPersistent = true;
                    extra.IssuedUtc = DateTime.UtcNow;
                    extra.ExpiresUtc = DateTime.UtcNow.AddDays(30);

                    var newTicket = new AuthenticationTicket(ticket.Identity, extra);

                    var cookieBuilder = new StringBuilder();
                    foreach (var cookie in cookies)
                    {
                        string value = cookie.Value;

                        if (cookie.Key == "jabbr.id")
                        {
                            // Create a new ticket preserving the identity of the user
                            // so they don't get logged out
                            value = _ticketHandler.Protect(newTicket);
                            response.AddCookie("jabbr.id", value, new CookieOptions
                            {
                                Expires = extra.ExpiresUtc.Value.UtcDateTime,
                                HttpOnly = true
                            });
                        }

                        if (cookieBuilder.Length > 0)
                        {
                            cookieBuilder.Append(";");
                        }

                        cookieBuilder.Append(cookie.Key)
                                     .Append("=")
                                     .Append(Uri.EscapeDataString(value));
                    }

                    headers["Cookie"] = new[] { cookieBuilder.ToString() };
                }
            }

            return _next(env);
        }
예제 #9
0
        /// <summary>
        /// Create a new wrapper.
        /// </summary>
        /// <param name="environment">OWIN environment dictionary which stores state information about the request, response and relevant server state.</param>
        public OwinContext(IDictionary <string, object> environment)
        {
            if (environment == null)
            {
                throw new ArgumentNullException("environment");
            }

            Environment = environment;
            Request     = new OwinRequest(environment);
            Response    = new OwinResponse(environment);
        }
예제 #10
0
        public void NoReconnectsAfterFallback()
        {
            // There was a regression where the SSE transport would try to reconnect after it times out.
            // This test ensures that no longer happens.
            // #2180
            using (var host = new MemoryHost())
            {
                var myReconnect = new MyReconnect();

                host.Configure(app =>
                {
                    Func<AppFunc, AppFunc> middleware = (next) =>
                    {
                        return env =>
                        {
                            var request = new OwinRequest(env);
                            var response = new OwinResponse(env);

                            if (!request.Path.Value.Contains("negotiate") && !request.QueryString.Value.Contains("longPolling"))
                            {
                                response.Body = new MemoryStream();
                            }

                            return next(env);
                        };
                    };

                    app.Use(middleware);

                    var config = new ConnectionConfiguration
                    {
                        Resolver = new DefaultDependencyResolver()
                    };

                    config.Resolver.Register(typeof(MyReconnect), () => myReconnect);

                    app.MapSignalR<MyReconnect>("/echo", config);
                });

                var connection = new Connection("http://foo/echo");

                using (connection)
                {
                    connection.Start(host).Wait();

                    // Give SSE an opportunity to reconnect
                    Thread.Sleep(TimeSpan.FromSeconds(5));

                    Assert.Equal(connection.State, ConnectionState.Connected);
                    Assert.Equal(connection.Transport.Name, "longPolling");
                    Assert.Equal(0, myReconnect.Reconnects);
                }
            }
        }
        public Task ProcessRequest(OwinRequest request)
        {
            byte[] resource = GetResource();

            var response = new OwinResponse(request.Environment)
            {
                ContentType = contentType,
                ContentLength = resource.Length
            };

            return response.WriteAsync(resource);
        }
 public override Task Invoke(IOwinContext context)
 {
     if (context.Request.Path == PathString.Empty || context.Request.Path == new PathString("/"))
     {
         return Task.Run(() =>
         {
             var response = new OwinResponse(context.Environment) {StatusCode = 502};
             response.Redirect(_url);
         });
     }
     return Next.Invoke(context);
 }
예제 #13
0
        public AppFunc DefaultApplication(AppFunc next)
        {
            return env =>
            {
                if (env.Get<string>("OwinDefaultMiddleWare") != "OwinDefaultMiddleWare" || env.Get<string>("Alpha") != "Alpha" || env.Get<string>("Beta") != "Beta")
                {
                    throw new Exception("Test failed to find appropriate custom value added by middleware");
                }

                OwinResponse response = new OwinResponse(env);
                return response.WriteAsync("SUCCESS");
            };
        }
예제 #14
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            string cookieValue = request.Cookies["jabbr.id"];
            if (!String.IsNullOrEmpty(cookieValue))
            {
                AuthenticationTicket ticket = _ticketHandler.Unprotect(cookieValue);
                if (ticket != null && ticket.Extra == null)
                {
                    var extra = new AuthenticationExtra();
                    extra.IsPersistent = true;
                    extra.IssuedUtc = DateTime.UtcNow;
                    extra.ExpiresUtc = DateTime.UtcNow.AddDays(30);

                    var newTicket = new AuthenticationTicket(ticket.Identity, extra);

                    var cookieBuilder = new StringBuilder();
                    foreach (var cookie in request.Cookies)
                    {
                        string value = cookie.Value;

                        if (cookie.Key == "jabbr.id")
                        {
                            // Create a new ticket preserving the identity of the user
                            // so they don't get logged out
                            value = _ticketHandler.Protect(newTicket);
                            response.Cookies.Append("jabbr.id", value, new CookieOptions
                            {
                                Expires = extra.ExpiresUtc.Value.UtcDateTime,
                                HttpOnly = true
                            });
                        }

                        if (cookieBuilder.Length > 0)
                        {
                            cookieBuilder.Append(";");
                        }

                        cookieBuilder.Append(cookie.Key)
                                     .Append("=")
                                     .Append(Uri.EscapeDataString(value));
                    }

                    request.Headers["Cookie"] = cookieBuilder.ToString();
                }
            }

            return _next(env);
        }
예제 #15
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var body = Encoding.UTF8.GetBytes("404");

            var response = new OwinResponse(env)
            {
                ReasonPhrase = "",
                StatusCode = 404,
                ContentType = "text/plain;charset=utf-8",
                ContentLength = body.Length
            };

            return response.WriteAsync(body);
        }
예제 #16
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            if (request.Uri.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) 
                return _next(env);

            var builder = new UriBuilder(request.Uri) { Scheme = "https" };

            if (request.Uri.IsDefaultPort)
                builder.Port = -1;

            response.Headers.Set("Location", builder.ToString());
            response.StatusCode = (int)HttpStatusCode.Found;

            return TaskHelper.Empty;
        }
        public Task ProcessRequest(OwinRequest request)
        {
            var result = action(GetRequestParams(request));
            var json = JsonConvert.SerializeObject(result);
            var jsonBytes = Encoding.UTF8.GetBytes(json);

            var response = new OwinResponse(request.Environment)
            {
                Headers =
                {
                    {"Cache-Control", new []{"no-store", "no-cache"}},
                    {"Pragma", new []{"no-cache"}}
                },
                ContentType = "application/json;charset=utf-8",
                ContentLength = jsonBytes.Length
            };

            return response.WriteAsync(jsonBytes);
        }
예제 #18
0
            public async Task InitMessageSentToFallbackTransports()
            {
                using (var host = new MemoryHost())
                {
                    host.Configure(app =>
                    {
                        Func<AppFunc, AppFunc> middleware = (next) =>
                        {
                            return env =>
                            {
                                var request = new OwinRequest(env);
                                var response = new OwinResponse(env);

                                if (!request.Path.Value.Contains("negotiate") && !request.QueryString.Value.Contains("longPolling"))
                                {
                                    response.Body = new MemoryStream();
                                }

                                return next(env);
                            };
                        };

                        app.Use(middleware);

                        var config = new ConnectionConfiguration
                        {
                            Resolver = new DefaultDependencyResolver()
                        };

                        app.MapSignalR<MyConnection>("/echo", config);
                    });

                    var connection = new Connection("http://foo/echo");

                    using (connection)
                    {
                        await connection.Start(host);

                        Assert.Equal(connection.State, ConnectionState.Connected);
                        Assert.Equal(connection.Transport.Name, "longPolling");
                    }
                }
            }
        public override Task ProcessRequest(HostContext context)
        {
            string redirectWhen = "____Never____";

            if (!String.IsNullOrEmpty(context.Request.QueryString["redirectWhen"]))
            {
                redirectWhen = context.Request.QueryString["redirectWhen"];
            }

            var owinRequest = new OwinRequest(context.Environment);

            if (owinRequest.Path.Value.Contains("/" + redirectWhen))
            {
                var response = new OwinResponse(context.Environment);

                // Redirect to an invalid page
                response.Redirect("http://" + owinRequest.Host);

                return TaskAsyncHelper.Empty;
            }

            return base.ProcessRequest(context);
        }
        public void ShouldFailOnCredentialsFuncException()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

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

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
                {
                    response.StatusCode = 401;
                    return Task.FromResult<object>(null);
                }),
               builder,
               new HawkAuthenticationOptions
               {
                   Credentials = (id) => { throw new Exception("Invalid"); }
               }
            );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Unknown user", logger.Messages[0]);
        }
예제 #21
0
 public abstract Task Invoke(OwinRequest request, OwinResponse response);
예제 #22
0
 public ServerResponse(IDictionary<string, object> environment)
 {
     _response = new OwinResponse(environment);
     _callCancelled = _response.Get<CancellationToken>(OwinConstants.CallCancelled);
     _responseBody = _response.Body;
 }
예제 #23
0
 public bool Equals(OwinResponse other)
 {
     return(Equals(_response, other._response));
 }
예제 #24
0
        /// <summary>
        /// OWIN entry point.
        /// </summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        public Task ProcessRequest(IDictionary<string, object> environment)
        {
            var context = new HostContext(environment);

            // Disable request compression and buffering on IIS
            environment.DisableRequestCompression();
            environment.DisableResponseBuffering();

            var response = new OwinResponse(environment);

            // Add the nosniff header for all responses to prevent IE from trying to sniff mime type from contents
            response.Headers.Set("X-Content-Type-Options", "nosniff");

            if (Authorize(context.Request))
            {
                return ProcessRequest(context);
            }

            if (context.Request.User != null &&
                context.Request.User.Identity.IsAuthenticated)
            {
                // If the user is authenticated and authorize failed then 403
                response.StatusCode = 403;
            }
            else
            {
                // If we failed to authorize the request then return a 401
                response.StatusCode = 401;
            }

            return TaskAsyncHelper.Empty;
        }
예제 #25
0
 public virtual Task Invoke(OwinRequest request, OwinResponse response)
 {
     return(Next.Invoke(request, response));
 }
        public void SendAsync_LeavesAuthenticationChallenges_WhenExistingAuthenticationTypesIsNonEmpty()
        {
            // Arrange
            IHostPrincipalService principalService = CreateStubPrincipalService();
            HttpMessageHandler inner = CreateStubHandler();
            HttpMessageHandler handler = CreateProductUnderTest(principalService, inner);
            IDictionary<string, object> environment = CreateOwinEnvironment();
            OwinResponse owinResponse = new OwinResponse(environment);
            AuthenticationExtra extraWrapper = new AuthenticationExtra();
            string[] expectedAuthenticationTypes = new string[] { "Existing" };
            IDictionary<string, string> expectedExtra = extraWrapper.Properties;
            owinResponse.AuthenticationResponseChallenge = new AuthenticationResponseChallenge(
                expectedAuthenticationTypes, extraWrapper);

            using (HttpRequestMessage request = CreateRequestWithOwinEnvironment(environment))
            {
                // Act
                handler.SendAsync(request, CancellationToken.None);
            }

            // Assert
            AuthenticationResponseChallenge challenge = owinResponse.AuthenticationResponseChallenge;
            Assert.NotNull(challenge);
            Assert.Same(expectedAuthenticationTypes, challenge.AuthenticationTypes);
            AuthenticationExtra actualExtraWrapper = challenge.Extra;
            Assert.NotNull(actualExtraWrapper);
            Assert.Same(expectedExtra, actualExtraWrapper.Properties);
        }
예제 #27
0
파일: Startup.cs 프로젝트: tkggand/katana
 public override Task Invoke(OwinRequest request, OwinResponse response)
 {
     return _appFunc.Invoke(response.Environment);
 }
        public void ShouldParseValidAuthHeaderWithSha256()
        {
            var credential = new HawkCredential
            {
                Id = "123",
                Algorithm = "hmacsha256",
                Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                User = "******"
            };

            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            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 = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "example.com" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                string.Format("id = \"456\", ts = \"{0}\", nonce=\"j4h3g2\", mac = \"{1}\", ext = \"hello\"",
                ts, mac)});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 200;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) => Task.FromResult(credential)
                           }
                        );

            middleware.Invoke(request, response);

            Assert.AreEqual(200, response.StatusCode);
            Assert.IsTrue(logger.Messages.Count == 0);
        }
        public void ShouldFailOnUnknownBadMac()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

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

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"/qwS4UjfVWMcU4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 401;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) =>
                               {
                                   return Task.FromResult(new HawkCredential
                                   {
                                       Id = "123",
                                       Algorithm = "hmacsha256",
                                       Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                                       User = "******"
                                   });
                               }
                           }
                        );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Bad mac", logger.Messages[0]);
        }
        public void ShouldFailOnUnknownAuthAttribute()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                "id = \"123\", ts = \"1353788437\", nonce = \"1353788437\", x = \"3\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                 new AppFuncTransition((env) =>
                 {
                     response.StatusCode = 401;
                     return Task.FromResult<object>(null);
                 }),
                builder,
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Unknown attributes", logger.Messages[0]);
        }
        public void ShouldReturnChallengeOnEmptyAuthHeaderWithStatusUnauthorized()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));

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

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                            new AppFuncTransition((env) =>
                            {
                                response.StatusCode = 401;
                                return Task.FromResult<object>(null);
                            }),
                           builder,
                           new HawkAuthenticationOptions
                           {
                               Credentials = (id) =>
                               {
                                   return Task.FromResult(new HawkCredential
                                   {
                                       Id = "123",
                                       Algorithm = "hmac-sha-0",
                                       Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                                       User = "******"
                                   });
                               }
                           }
                        );

            middleware.Invoke(request, response);

            Assert.AreEqual(401, response.StatusCode);
            Assert.IsNotNull(((IDictionary<string, string[]>)response.Environment["owin.ResponseHeaders"])["WWW-Authenticate"]);
        }
        /// <summary>
        /// Creates request OWIN respresentation. 
        /// </summary>
        /// <param name="method">The request method.</param>
        /// <param name="scheme">The request scheme.</param>
        /// <param name="pathBase">The request base path.</param>
        /// <param name="path">The request path.</param>
        /// <param name="headers">The request headers.</param>
        /// <param name="queryString">The request query string</param>
        /// <param name="requestBody">The body of request.</param>
        /// <returns>OWIN representation for provided request parameters.</returns>
        private static Dictionary<string, object> CreateOwinEnvironment(string method, string scheme, string pathBase, 
                                                                        string path, IDictionary<string, string[]> headers, string queryString = "", byte[] requestBody = null)
        {
            var environment = new Dictionary<string, object>(StringComparer.Ordinal);
            environment[CommonOwinKeys.OwinCallCancelled] = new CancellationToken();

            #region OWIN request params

            var request = new OwinRequest(environment)
                {
                    Method = method,
                    Scheme = scheme,
                    Path = new PathString(path),
                    PathBase = new PathString(pathBase),
                    QueryString = new QueryString(queryString),
                    Body = new MemoryStream(requestBody ?? new byte[0]),
                    Protocol = Protocols.Http1
                };

            // request.Headers is readonly
            request.Set(CommonOwinKeys.RequestHeaders, headers);

            #endregion


            #region set default OWIN response params

            var response = new OwinResponse(environment) {Body = new MemoryStream(), StatusCode = StatusCode.Code200Ok};
            //response.Headers is readonly
            response.Set(CommonOwinKeys.ResponseHeaders, new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase));

            #endregion


            return environment;
        }
        public void ShouldSkipAuthOnWrongAuthScheme()
        {
            var builder = new AppBuilderFactory().Create();

            var request = OwinRequest.Create();
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Basic " });

            var response = new OwinResponse(request);

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
                    {
                        response.StatusCode = 200;
                        return Task.FromResult<object>(null);
                    }),
                builder,
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(request, response);

            Assert.IsNotNull(response);
            Assert.AreEqual(200, response.StatusCode);
        }
예제 #34
0
 public bool Equals(OwinResponse other)
 {
     return Equals(_response, other._response);
 }
        public void SendAsync_SuppressesAuthenticationChallenges_WhenNoChallengeIsSet()
        {
            // Arrange
            IHostPrincipalService principalService = CreateStubPrincipalService();
            HttpMessageHandler inner = CreateStubHandler();
            HttpMessageHandler handler = CreateProductUnderTest(principalService, inner);
            IDictionary<string, object> environment = CreateOwinEnvironment();

            using (HttpRequestMessage request = CreateRequestWithOwinEnvironment(environment))
            {
                // Act
                handler.SendAsync(request, CancellationToken.None);
            }

            // Assert
            OwinResponse owinResponse = new OwinResponse(environment);
            AuthenticationResponseChallenge challenge = owinResponse.AuthenticationResponseChallenge;
            Assert.NotNull(challenge);
            string[] authenticationTypes = challenge.AuthenticationTypes;
            Assert.NotNull(authenticationTypes);
            Assert.Equal(1, authenticationTypes.Length);
            string authenticationType = authenticationTypes[0];
            Assert.Null(authenticationType);
        }