Ejemplo n.º 1
1
        public ServerRequest(IDictionary<string, object> environment)
        {
            _request = new OwinRequest(environment);

            // Cache user because AspNetWebSocket.CloseOutputAsync clears it. We need it during Hub.OnDisconnected
            _user = _request.User;
        }
Ejemplo n.º 2
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);
            }
        }
Ejemplo n.º 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";
        }
        public Task Invoke(IDictionary<string, object> env)
        {
            try
            {
                var request = new OwinRequest(env);
                var path = request.Path.ToString();

                logger.Info("Execute action: {0};", path);

                IListenerHandler handler;
                if (handlers.TryGetValue(path, out handler))
                    return handler.ProcessRequest(request);
                else
                    logger.Info(string.Format("Handler for url '{0}' is not found", path));
            }
            catch (Exception ex)
            {
                logger.Error(ex, "");

                var tcs = new TaskCompletionSource<object>();
                tcs.SetException(ex);
                return tcs.Task;
            }

            return next(env);
        }
Ejemplo n.º 5
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();
        }
        private static HttpRequestParams GetRequestParams(OwinRequest request)
        {
            var task = request.ReadFormAsync();
            task.Wait();

            return new HttpRequestParams(request.Query, task.Result);
        }
        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);
        }
Ejemplo n.º 8
0
        /// <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 static object HookAuthentication(this OwinRequest request, IAuthenticationHandler handler)
        {
            var chained = request.Get <AuthenticateDelegate>("security.Authenticate");
            var hook    = new Hook(handler, chained);

            request.Set <AuthenticateDelegate>("security.Authenticate", hook.Authenticate);
            return(hook);
        }
 public OwinCommunicationContext(IOwinContext nativeContext,ILogger logger)
 {
     PipelineData = new PipelineData();
     _nativeContext = nativeContext;
     Request = new OwinRequest(nativeContext.Request);
     Response = new OwinResponse(nativeContext);
     ServerErrors = new ServerErrorList { Log = logger };
     User = nativeContext.Request.User;
 }
Ejemplo n.º 11
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);
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
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);
                }
            }
        }
Ejemplo n.º 14
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);
        }
        public void TestGetClientIpAddressFromOwinContext()
        {
            var owinContextStub = MockRepository.GenerateMock<OwinContext>();
            var owinRequest = new OwinRequest { RemoteIpAddress = "127.0.0.1" };
            owinContextStub.Stub(x => x.Request).Return(owinRequest).Repeat.Once();
            var httpRequestMessage = new HttpRequestMessage();
            httpRequestMessage.Properties.Add("MS_OwinContext", owinContextStub);

            var result = httpRequestMessage.GetClientIpAddress();

            Assert.That(result, Is.EqualTo("127.0.0.1"));
        }
        public Task ProcessRequest(OwinRequest request)
        {
            byte[] resource = GetResource();

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

            return response.WriteAsync(resource);
        }
        public string GetCommandName()
        {
            var request = new OwinRequest(OwinRequestScopeContext.Current.Environment);
            var commandHeader = request.Headers.FirstOrDefault(x => x.Key.Equals(CommandHeaderKey, StringComparison.InvariantCultureIgnoreCase));

            if (commandHeader.Key != null)
            {
                var commandName = commandHeader.Value.Single();
                return commandName;
            }

            return null;
        }
        public string GetCommandName(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);
            var commandHeader = request.Headers.FirstOrDefault(x => x.Key.Equals(CommandHeaderKey, StringComparison.InvariantCultureIgnoreCase));

            if (commandHeader.Key != null)
            {
                var commandName = commandHeader.Value.Single();
                return commandName;
            }

            return null;
        }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
0
        public Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);

            // This header is set on app harbor since ssl is terminated at the load balancer
            var scheme = request.Headers.Get("X-Forwarded-Proto");

            if (!String.IsNullOrEmpty(scheme))
            {
                request.Scheme = scheme;
            }

            return _next(env);
        }
Ejemplo n.º 21
0
        public string GetCommandName(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);

            var commandEndpointPath = (PathString) environment["CommandEndpointPath"];
            var requestPath = new PathString(request.Uri.LocalPath);

            PathString remainingPath;
            if (requestPath.StartsWithSegments(commandEndpointPath, out remainingPath))
            {
                var commandName = remainingPath.Value.TrimStart('/');
                return commandName;
            }

            return null;
        }
 public object Create(Type commandType, IDictionary<string, object> environment)
 {
     var request = new OwinRequest(environment);
     using (var streamReader = new StreamReader(request.Body))
     {
         var requestBody = streamReader.ReadToEnd();
         try
         {
             var command = Convert.ChangeType(JsonConvert.DeserializeObject(requestBody, commandType), commandType);
             return command;
         }
         catch (JsonReaderException ex)
         {
             throw new CommandConstructionException(commandType, requestBody, ex);
         }
     }
 }
Ejemplo n.º 23
0
        public string GetCommandName()
        {
            var environment = OwinRequestScopeContext.Current.Environment;
            var request = new OwinRequest(environment);

            var commandEndpointPath = (PathString) environment["CommandEndpointPath"];
            var requestPath = new PathString(request.Uri.LocalPath);

            PathString remainingPath;
            if (requestPath.StartsWithSegments(commandEndpointPath, out remainingPath))
            {
                var commandName = remainingPath.Value.TrimStart('/');
                return commandName;
            }

            return null;
        }
Ejemplo n.º 24
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;
        }
Ejemplo n.º 25
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 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);
        }
        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);
        }
        /// <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;
        }
Ejemplo n.º 29
0
 public override Task Invoke(OwinRequest request, OwinResponse response)
 {
     return _appFunc.Invoke(response.Environment);
 }
Ejemplo n.º 30
0
 public bool Equals(OwinRequest other)
 {
     return(Equals(_request, other._request));
 }
Ejemplo n.º 31
0
 public abstract Task Invoke(OwinRequest request, OwinResponse response);
 public RequestHandler(IDictionary<string, object> owinEnvironment)
 {
     Console.WriteLine("RequestHandler ctor");
     OwinRequest req = new OwinRequest(owinEnvironment);
     Console.WriteLine(req.Uri.AbsoluteUri);
 }
Ejemplo n.º 33
0
 public OwinResponse(OwinRequest request) : this(request.Environment)
 {
 }
        public override Task Invoke(OwinRequest request, OwinResponse response)
        {
            response.AddHeader("X-ApplicationVersion", BuildInfo.Version.ToString());

            return Next.Invoke(request, response);
        }
        public static void UnhookAuthentication(this OwinRequest request, object state)
        {
            var hook = (Hook)state;

            request.Set("security.Authenticate", hook.Chained);
        }
Ejemplo n.º 36
0
 public RazorRequest(IDictionary<string, object> environment)
 {
     _request = new OwinRequest(environment);
 }
Ejemplo n.º 37
0
 public OwinResponse(OwinRequest request) : this(request.Environment)
 {
 }
Ejemplo n.º 38
0
 public virtual Task Invoke(OwinRequest request, OwinResponse response)
 {
     return(Next.Invoke(request, response));
 }