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

            var logger = _kernel.Get<ILogger>();

            var requestHeaders = new StringBuilder();
            foreach (var header in request.Headers)
            {
                requestHeaders.AppendLine(header.Key + " = " + request.GetHeader(header.Key));
            }

            Task task = _next(env);

            var response = new OwinResponse(env);

            var responseHeaders = new StringBuilder();
            foreach (var header in response.Headers)
            {
                responseHeaders.AppendLine(header.Key + " = " + response.GetHeader(header.Key));
            }

            logger.Log("URI: " + request.Uri + " " + Environment.NewLine +
                       "Request Headers: \r\n " + requestHeaders.ToString() + Environment.NewLine +
                       "Response Headers: \r\n " + responseHeaders.ToString());

            return task;
        }
        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.SetHeader("Location", builder.ToString());
                response.StatusCode = 302;

                return TaskAsyncHelper.Empty;
            }
            else
            {
                return _next(env);
            }
        }
        public Task Invoke(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);
            if (string.IsNullOrEmpty(_options.Path) || string.Equals(request.Path, _options.Path, StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make it pretty
                OwinResponse response = new OwinResponse(environment);
                response.ContentType = "text/html";

                StringBuilder builder = new StringBuilder();
                builder.AppendLine("<html>")

                .AppendLine("<head>")
                .AppendLine("<title>")
                .AppendLine("Welcome")
                .AppendLine("</title>")
                .AppendLine("</head>")

                .AppendLine("<body>")
                .AppendLine("<H1>Welcome</H1>")
                .AppendLine("<p>You have reached the default application page.</p>")
                .AppendLine("<H4>Additional Resources:</H4>")
                .AppendLine("<ul>")
                .AppendLine("<li><a href=\"http://katanaproject.codeplex.com/\">Katana Project</a>")
                .AppendLine("<li><a href=\"http://www.owin.org/\">owin.org</a>")
                .AppendLine("</ul>")
                .AppendLine("</body>")
                .AppendLine("</html>");
                return response.WriteAsync(builder.ToString());
            }
            return _next(environment);
        }
 public async Task<string> GetTemplate(OwinRequest request)
 {
     using (var reader = new StreamReader(file.CreateReadStream()))
     {
         return await reader.ReadToEndAsync();
     }
 }
Exemple #5
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            var request = new OwinRequest(env);
            var response = new OwinResponse(env);

            int id;
            if (int.TryParse(request.Path.Substring(1), out id))
            {
                switch (request.Method)
                {
                    case "GET":
                        var job = await _jobList.GetJob(id);
                        JsonSerializer.SerializeToStream(job, response.Body);
                        break;
                    case "DELETE":
                        _jobList.DeleteJob(id);
                        break;
                    default:
                        throw new NotImplementedException();
                }
            }
            else
            {
                JsonSerializer.SerializeToStream(await _jobList.ListJobs(), response.Body);
            }
        }
        public static IDictionary<string, object> WithHeader(this IDictionary<string, object> env, string key, string value)
        {
            var request = new OwinRequest(env);
            request.SetHeader(key, value);

            return request.Dictionary;
        }
Exemple #7
0
 public Func<OwinRequest, object> GetMatch(OwinRequest request)
 {
     var match = _routeHandlers
                 .Where(rvp => rvp.Key.HasMatch(request))
                 .OrderByDescending(rvp => rvp.Key.Specificity)
                 .Select(rvp => rvp.Value).FirstOrDefault();
     return match;
 }
        public static IDictionary<string, object> WithBody(this IDictionary<string, object> env, Stream stream)
        {
            var request = new OwinRequest(env);
            request.Body = stream;
            request.SetHeader("Content-Length", stream.Length.ToString());

            return request.Dictionary;
        }
 private static void BuildRequestFromUri(OwinRequest request, Uri uri)
 {
     request.Host = uri.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
     request.PathBase = String.Empty;
     request.Path = uri.LocalPath;
     request.Scheme = uri.Scheme;
     request.QueryString = uri.Query.Length > 0 ? uri.Query.Substring(1) : String.Empty;
 }
        Task UpgradeToWebSockets(OwinRequest request, OwinResponse response, Func<Task> next)
        {
            if (!request.CanAccept)
                return next();

            request.Accept(WebSocketEcho);

            return Task.FromResult<object>(null);
        }
        public void Init()
        {
            table = new Mock<IRouteTable>();
            renderer = new Mock<IRazorRenderer>();
            request = new OwinRequest(new Dictionary<string, object>());
            response = new OwinResponse(new Dictionary<string, object>()) { Headers = new Dictionary<string, string[]>(), Body = new MemoryStream() };

            middleware = new RazorMiddleware(table.Object, renderer.Object);
        }
Exemple #12
0
 static AppFunc LogBefore(AppFunc next)
 {
     return env =>
         {
             var request = new OwinRequest(env);
             Console.WriteLine("{0} {1}", request.Method, request.Path);
             return next(env);
         };
 }
 private ICompressedStorage GetStorageOnce(IDictionary<string, object> environment)
 {
     ICompressedStorage storage = _options.CompressedStorageProvider.Create();
     var onAppDisposing = new OwinRequest(environment).Get<CancellationToken>("host.OnAppDisposing");
     if (onAppDisposing != CancellationToken.None)
     {
         onAppDisposing.Register(storage.Dispose);
     }
     return storage;
 }
 public Task Invoke(IDictionary<string, object> environment)
 {
     var request = new OwinRequest(environment);
     if (_routeMatcher.HasMatch(request))
     {
         var response = new OwinResponse(environment);
         var routeHandler = _routeMatcher.GetMatch(request);
         return InvokeHandler(response, routeHandler, request);
     }
     return _next(environment);
 }
        public Task Invoke(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);

            var handler = FindHandler(request.Method, request.Path);

            if (handler == null)
                return _next(environment);

            return handler(environment, _next);
        }
 private static Task InvokeHandler(OwinResponse res, Func<OwinRequest, object> routeHandler, OwinRequest req)
 {
     var result = routeHandler(req);
     var flaskyResponse = result as IResponse;
     if(flaskyResponse != null)
     {
         return flaskyResponse.Write(res);
     }
     res.ContentType = "text/plain";
     return res.WriteAsync(result.ToString());
 }
Exemple #17
0
 public bool HasMatch(OwinRequest request)
 {
     switch (_setting)
     {
         case RouteSetting.Path :
             return HasMatch(request.Path);
         case RouteSetting.PathAndMethod:
             return HasMatch(request.Path) && _method.Equals(request.Method, StringComparison.OrdinalIgnoreCase);
     }
     return false;
 }
 public StaticCompressionContext(IDictionary<string, object> environment, StaticCompressionOptions options, IEncoding encoding, ICompressedStorage storage)
 {
     _environment = environment;
     _options = options;
     _encoding = encoding;
     _encodingSuffix = "^" + _encoding.Name;
     _encodingSuffixQuote = "^" + _encoding.Name + "\"";
     _storage = storage;
     _request = new OwinRequest(environment);
     _response = new OwinResponse(environment);
 }
 public Task Invoke(IDictionary<string, object> env)
 {
     var request = new OwinRequest(env);
     var response = new OwinResponse(env);
     if (!request.IsLocal)
     {
         response.StatusCode = (int)HttpStatusCode.ServiceUnavailable;
         return Task.FromResult(0);
     }
     return _next(env);
 }
        private bool IsRequestForHttp2Upgrade(OwinRequest request)
        {
            // TODO: Supported methods?  None called out in the 01 spec, but the sample uses GET.
            // POST would be problematic as you'd also have to consume all of the request data before completing the upgrade.

            // Headers
            // Connection: Upgrade
            // Upgrade: HTTP/2.0
            return string.Equals(request.GetHeader("Connection"), "Upgrade", StringComparison.OrdinalIgnoreCase)
                && string.Equals(request.GetHeader("Upgrade"), "HTTP/2.0", StringComparison.OrdinalIgnoreCase);
        }
 public Task Invoke(IDictionary<string, object> environment)
 {
     var request = new OwinRequest(environment);
     if (string.IsNullOrEmpty(_options.Path) || string.Equals(request.Path, _options.Path, StringComparison.OrdinalIgnoreCase))
     {
         // TODO: Make it pretty
         OwinResponse response = new OwinResponse(environment);
         response.ContentType = "text/plain";
         return response.WriteAsync("Welcome to Katana");
     }
     return _next(environment);
 }
        public Task Invoke(IDictionary<string, object> environment)
        {
            OwinRequest request = new OwinRequest(environment);
            OwinResponse response = new OwinResponse(environment);

            response.ContentType = "text/plain";

            string responseText = request.GetHeader("breadcrumbs") + "\r\n"
                + "PathBase: " + request.PathBase + "\r\n"
                + "Path: " + request.Path + "\r\n";

            return response.WriteAsync(responseText);
        }
        public async Task Invoke(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);
            Uri uri = request.Uri;

            // Create a stream for the host and port so we can send the request
            Stream stream = await _streamFactory.CreateStream(uri).ConfigureAwait(continueOnCapturedContext: false);

            var requestWriter = new StreamWriter(stream);

            // Request line
            requestWriter.WriteLine("{0} {1} {2}", request.Method, uri.LocalPath, request.Protocol);

            // Write headers
            foreach (var header in request.Headers)
            {
                requestWriter.WriteLine("{0}: {1}", header.Key, request.GetHeader(header.Key));
            }

            // End headers
            requestWriter.WriteLine();

            if (request.Body == null)
            {
                // End request
                requestWriter.WriteLine();
            }

            // Flush buffered content to the stream async
            await requestWriter.FlushAsync().ConfigureAwait(continueOnCapturedContext: false);

            if (request.Body != null)
            {
                // Copy the body to the request
                await request.Body.CopyToAsync(stream).ConfigureAwait(continueOnCapturedContext: false);
            }

            var response = new OwinResponse(environment);

            // Parse the response
            HttpParser.ParseResponse(stream, (protocol, statusCode, reasonPhrase) =>
            {
                response.Protocol = protocol;
                response.StatusCode = statusCode;
                response.ReasonPhrase = reasonPhrase;
            },
            (key, value) => response.SetHeader(key, value));

            // Set the body to the rest of the stream
            response.Body = stream;
        }
Exemple #24
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.GetHeader("X-Forwarded-Proto");

            if (!String.IsNullOrEmpty(scheme))
            {
                env[OwinConstants.RequestScheme] = scheme;
            }

            return _next(env);
        }
Exemple #25
0
            public async Task Invoke(IDictionary<string, object> env) {

                OwinRequest request = new OwinRequest(env);
                if (request.Path == "/raw") {

                    OwinResponse response = new OwinResponse(request);
                    response.ContentType = "text/plain";
                    await response.WriteAsync("Hello from OWIN!");
                }
                else {

                    await _nextFunc(env);
                }
            }
        public async Task Invoke(IDictionary<string, object> env)
        {
            object value;
            if (env.TryGetValue("server.User", out value))
            {
                var windowsPrincipal = value as WindowsPrincipal;
                if (windowsPrincipal != null && windowsPrincipal.Identity.IsAuthenticated)
                {
                    await _next(env);

                    var request = new OwinRequest(env);
                    var response = new OwinResponse(env);

                    if (response.StatusCode == 401)
                    {
                        // We're going no add the identifier claim
                        var nameClaim = windowsPrincipal.FindFirst(ClaimTypes.Name);

                        // This is the domain name
                        string name = nameClaim.Value;

                        // If the name is something like DOMAIN\username then
                        // grab the name part
                        var parts = name.Split(new[] { '\\' }, 2);

                        string shortName = parts.Length == 1 ? parts[0] : parts[parts.Length - 1];

                        // REVIEW: Do we want to preserve the other claims?

                        // Normalize the claims here
                        var claims = new List<Claim>();
                        claims.Add(new Claim(ClaimTypes.NameIdentifier, name));
                        claims.Add(new Claim(ClaimTypes.Name, shortName));
                        claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "Windows"));
                        var identity = new ClaimsIdentity(claims, Constants.JabbRAuthType);
                        var claimsPrincipal = new ClaimsPrincipal(identity);

                        response.SignIn(claimsPrincipal);

                        response.StatusCode = 302;
                        response.SetHeader("Location", request.PathBase + request.Path);
                    }

                    return;
                }
            }

            await _next(env);
        }
        public static AppFunc Middleware(AppFunc app)
        {
            return env =>
            {
                var request = new OwinRequest(env);
                var websocketVersion = request.Get<string>(OwinConstants.WebSocket.Version);
                WebSocketAccept webSocketAccept = request.Get<WebSocketAccept>(OwinConstants.WebSocket.Accept);

                if (request.CanUpgrade && websocketVersion == null) // If we have opaque support and no WebSocket support yet
                {
                    if (IsWebSocketRequest(env))
                    {
                        // TODO: check for correct requested version of WebSocket protocol
                        IDictionary<string, object> acceptOptions = null;
                        WebSocketFunc webSocketFunc = null;

                        // Announce websocket support
                        env[OwinConstants.WebSocket.Accept] = new WebSocketAccept(
                            (options, callback) =>
                            {
                                acceptOptions = options;
                                webSocketFunc = callback;
                                env[OwinConstants.ResponseStatusCode] = 101;
                            });

                        return app(env).ContinueWith(t =>
                        {
                            OwinResponse response = new OwinResponse(env);
                            if (response.StatusCode == 101
                                && webSocketFunc != null)
                            {
                                SetWebSocketResponseHeaders(env, acceptOptions);

                                request.UpgradeDelegate(acceptOptions, opaqueEnv =>
                                {
                                    WebSocketLayer webSocket = new WebSocketLayer(opaqueEnv);
                                    return webSocketFunc(webSocket.Environment)
                                        .ContinueWith(tt => webSocket.CleanupAsync());
                                });
                            }
                        });
                    }
                }

                // else
                return app(env);
            };
        }
        private string BuildRedirectUrl(OwinResponse response)
        {
            string location = response.GetHeader("Location");

            Uri uri;
            if (Uri.TryCreate(location, UriKind.Relative, out uri))
            {
                // If location is relative, we need to build a full url
                var previousRequest = new OwinRequest(response.Dictionary);
                var uriBuilder = new UriBuilder(previousRequest.Uri);
                uriBuilder.Path = location;

                return uriBuilder.ToString();
            }

            return location;
        }
        /// <summary></summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        public async Task Invoke(IDictionary<string, object> environment)
        {
            OwinRequest request = new OwinRequest(environment);
            OwinResponse response = new OwinResponse(environment);
            CancellationToken cancellationToken = request.CallCancelled;

            AuthenticationHeaderValue authorization;
            string authorizationHeaderError;

            if (!TryParseAuthorizationHeader(request, out authorization, out authorizationHeaderError))
            {
                response.StatusCode = 400;
                cancellationToken.ThrowIfCancellationRequested();
                await WriteMessage(authorizationHeaderError, response, cancellationToken);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            IBasicAuthenticationResult result = await AuthenticateAsync(authorization, cancellationToken);

            int errorStatusCode;
            string errorMessage;

            if (!TryProcessResult(result, environment, out errorStatusCode, out errorMessage))
            {
                response.StatusCode = errorStatusCode;
                cancellationToken.ThrowIfCancellationRequested();
                await AddChallengeOnUnauthorizedAsync(response, cancellationToken);
                cancellationToken.ThrowIfCancellationRequested();
                await WriteMessage(errorMessage, response, cancellationToken);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            AuthenticationHeaderValue challenge = await _protocol.CreateChallengeAsync(cancellationToken);
            if (!TryRegisterOnSendingHeaders(challenge, request, response, out errorMessage))
            {
                response.StatusCode = 500;
                cancellationToken.ThrowIfCancellationRequested();
                await WriteMessage(errorMessage, response, cancellationToken);
                return;
            }

            cancellationToken.ThrowIfCancellationRequested();
            await _next(environment);
        }
        private static Task RequestDump(OwinRequest request, OwinResponse response)
        {
            var builder = new StringBuilder();
            builder.AppendLine("<h1>Katana demo op TechDays</h1>");
            builder.AppendLine("<h2>request.Dictionary</h2>");

            builder.Append("<table>");
            foreach (var item in request.Dictionary)
            {
                builder.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>",
                    item.Key, item.Value);
            }
            builder.Append("</table>");

            response.ContentType = "text/html";
            return response.WriteAsync(builder.ToString());
        }
 public bool Equals(OwinRequest other)
 {
     return(Equals(_dictionary, other._dictionary));
 }
Exemple #32
0
 public OwinResponse(OwinRequest request)
 {
     _dictionary = request.Dictionary;
 }