public void When_matcher_is_asked_to_return_a_request_handler_that_is_set_up_that_handler_is_returned()
        {
            const string testResponse = "test-response";

            var routeHandlers = new Dictionary <RouteBase, Func <OwinRequest, object> >
            {
                {
                    new RegexRoute("foo/"), r =>
                    {
                        return(testResponse);
                    }
                }
            };

            var matcher = new RouteMatcher(routeHandlers);

            var request = OwinRequest.Create();

            request.Path = "foo/";

            Assert.That(matcher.HasMatch(request), Is.True);
            var handler = matcher.GetMatch(request);

            Assert.That(handler(request).ToString(), Is.EqualTo(testResponse));
        }
Beispiel #2
0
        private static OwinRequest Create(Action <OwinRequest> setup)
        {
            var request = OwinRequest.Create();

            setup(request);
            return(request);
        }
Beispiel #3
0
        /// <summary>
        /// Reads and parses the request body as a form.
        /// </summary>
        /// <returns>The parsed form data.</returns>
        internal static IFormCollection ReadForm(this OwinRequest request)
        {
            var form = request.Get <IFormCollection>("Microsoft.Owin.Form#collection");

            if (form == null)
            {
                request.Body.Seek(0, SeekOrigin.Begin);

                string text;

                // Don't close, it prevents re-winding.
                using (var reader = new StreamReader(request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4 * 1024, leaveOpen: true))
                {
                    text = reader.ReadToEnd();
                }

                // re-wind for the next caller
                request.Body.Seek(0, SeekOrigin.Begin);

                form = OwinHelpers.GetForm(text);
                request.Set("Microsoft.Owin.Form#collection", form);
            }

            return(form);
        }
        public RequestHandler(IDictionary <string, object> owinEnvironment)
        {
            Console.WriteLine("RequestHandler ctor");
            OwinRequest req = new OwinRequest(owinEnvironment);

            Console.WriteLine(req.Uri.AbsoluteUri);
        }
Beispiel #5
0
        /// <summary>
        /// Extracts the username and password from a basic Authorize header. Returns false if the header
        /// is missing or badly formatted.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        private bool ExtractCredentials(OwinRequest request, ref string userName, ref string password)
        {
            var result = false;

            var authorizationMime64 = request.Headers["Authorization"] ?? "";

            if (authorizationMime64 != "")
            {
                const string basicScheme = "Basic ";
                if (authorizationMime64.StartsWith(basicScheme, StringComparison.OrdinalIgnoreCase))
                {
                    var usernamePassword   = authorizationMime64.Substring(basicScheme.Length).Trim();
                    var authorizationBytes = Convert.FromBase64String(usernamePassword);
                    var authorization      = Encoding.UTF8.GetString(authorizationBytes);

                    var separatorPosn = authorization.IndexOf(':');
                    if (separatorPosn != -1)
                    {
                        userName = authorization.Substring(0, separatorPosn);
                        password = authorization.Substring(separatorPosn + 1);

                        result = userName.Length > 0;
                    }
                }
            }

            return(result);
        }
Beispiel #6
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);
        }
Beispiel #7
0
        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]);
        }
Beispiel #8
0
        public void ReadFromStreamTwice()
        {
            var stream = new MemoryStream();
            var writer = new StreamWriter(stream);

            writer.Write(OriginalFormsString);
            writer.Flush();
            stream.Seek(0, SeekOrigin.Begin);
            IOwinRequest request = new OwinRequest();

            request.Body = stream;
            IFormCollection form = request.ReadFormAsync().Result;

            Assert.Equal("v1", form.Get("q1"));
            Assert.Equal("v2,b", form.Get("Q2"));
            Assert.Equal("v3,v4", form.Get("q3"));
            Assert.Null(form.Get("q4"));
            Assert.Equal("v5,v5", form.Get("Q5"));

            form = request.ReadFormAsync().Result;
            Assert.Equal("v1", form.Get("q1"));
            Assert.Equal("v2,b", form.Get("Q2"));
            Assert.Equal("v3,v4", form.Get("q3"));
            Assert.Null(form.Get("q4"));
            Assert.Equal("v5,v5", form.Get("Q5"));
        }
Beispiel #9
0
        public static Task Invoke(IOwinContext context, Func <IOwinContext, Task> next)
        {
            var request  = new OwinRequest(context.Environment);
            var segments = request.Uri.Segments;
            var raw      = String.Join(null, segments);

            var matches =
                from builder in _builders
                from key in builder.RoutesKeys
                let matcher                         = new Regex(String.Format("^/{0}/{1}/?$", builder.Prefix, ToRegex(key)))
                                          let match = matcher.Match(raw)
                                                      where match.Success
                                                      let groups = match
                                                                   .Groups
                                                                   .Cast <Group>()
                                                                   .Index()
                                                                   let @params = (from g in groups
                                                                                  select new KeyValuePair <string, string>(
                                                                                      matcher.GroupNameFromNumber(g.Key),
                                                                                      g.Value.Value))
                                                                                 select new
            {
                Params = @params.Skip(1).ToDictionary(k => k.Key, v => v.Value),
                Route  = builder.Routes[key]
            };

            var invocation = matches.FirstOrDefault();

            return(invocation != null
                ? invocation.Route.Invoke(context.Environment, invocation.Params)
                : next(context));
        }
Beispiel #10
0
        public Task Invoke(IDictionary <string, object> environment)
        {
            OwinRequest request = new OwinRequest(environment);

            request.AddHeader("breadcrumbs", _breadcrumb);
            return(_next(environment));
        }
Beispiel #11
0
        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;
        }
Beispiel #12
0
        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))
                {
                    //var message = string.Format("handler for url '{0}' is not found", localPath);
                    return(handler.ProcessRequest(request));
                }
            }
            catch (Exception ex)
            {
                var tcs = new TaskCompletionSource <object>();
                tcs.SetException(ex);
                logger.ErrorException("", ex);
                return(tcs.Task);
            }

            return(next(env));
        }
        public static string GetForwardedScheme(OwinRequest request)
        {
            var headers = request.Headers;

            var forwardedSsl = GetHeader(headers, "X-Forwarded-Ssl");
            if (forwardedSsl != null && string.Equals(forwardedSsl, "on", StringComparison.OrdinalIgnoreCase))
            {
                return "https";
            }

            var forwardedScheme = GetHeader(headers, "X-Forwarded-Scheme");
            if (!string.IsNullOrWhiteSpace(forwardedScheme))
            {
                return forwardedScheme;
            }

            var forwardedProto = GetHeaderSplit(headers, "X-Forwarded-Proto");
            if (forwardedProto != null)
            {
                forwardedScheme = forwardedProto.FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(forwardedScheme))
                {
                    return forwardedScheme;
                }
            }

            return request.Scheme;
        }
Beispiel #14
0
        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);
        }
        public override async Task Invoke(IOwinContext context)
        {
            IRequest          owinRequest      = new OwinRequest(context.Request.Query, await context.Request.ReadFormAsync());
            IResponseRenderer responseRenderer = new OwinResponseRenderer(context);

            _runningApplication.Handle(owinRequest, responseRenderer);
        }
Beispiel #16
0
        private RaygunIdentifierMessage GetRaygunIdentifierForNancyContext(OwinRequest request)
        {
            var context = request.Get <NancyContext>("nancy.NancyContext");

            if (context == null || context.CurrentUser == null)
            {
                return(null);
            }

            var user = context.CurrentUser as UserIdentity;

            if (user == null)
            {
                return(null);
            }

            var userId = user.UserId.ToString("D");

            return(new RaygunIdentifierMessage(user.UserName)
            {
                Email = string.Format("{0}@raygunio.test", user.UserName),
                FirstName = "robbie",
                FullName = "robbie the robot",
                IsAnonymous = false,
                UUID = userId
            });
        }
Beispiel #17
0
            private static async Task ExecuteAsync(
                IDictionary <string, object> environment,
                IDictionary <string, string> keys, OwinRequest request,
                AsyncHttpRequestHandler handler)
            {
                var response = new OwinResponse(environment);

                var executor = (Func <Task <object> >)(async() =>
                {
                    var form = from w in request.HasForm()
                                         ? (IEnumerable <KeyValuePair <string, string[]> >)(await request.ReadFormAsync().ConfigureAwait(false))
                                         : EmptyForm
                               select w != null ? w[0] : null;

                    return(await handler.Executor(
                               environment,
                               keys,
                               form.ToDictionary()));
                });

                var result = await executor().ConfigureAwait(false);

                if (result != null)
                {
                    await response.WriteAsync(JsonConvert.SerializeObject(result)).ConfigureAwait(false);
                }

                response.StatusCode = handler.StatusCodeGenerator != null
                                    ? handler.StatusCodeGenerator(result)
                                    : (int)HttpStatusCode.OK;
            }
        public static string GetForwardedScheme(OwinRequest request)
        {
            var headers = request.Headers;

            var forwardedSsl = GetHeader(headers, "X-Forwarded-Ssl");

            if (forwardedSsl != null && string.Equals(forwardedSsl, "on", StringComparison.OrdinalIgnoreCase))
            {
                return("https");
            }

            var forwardedScheme = GetHeader(headers, "X-Forwarded-Scheme");

            if (!string.IsNullOrWhiteSpace(forwardedScheme))
            {
                return(forwardedScheme);
            }

            var forwardedProto = GetHeaderSplit(headers, "X-Forwarded-Proto");

            if (forwardedProto != null)
            {
                forwardedScheme = forwardedProto.FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(forwardedScheme))
                {
                    return(forwardedScheme);
                }
            }

            return(request.Scheme);
        }
Beispiel #19
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);
        }
Beispiel #20
0
        private RequestInstance BuildRequest(Action <OwinRequest> configure)
        {
            OwinRequest request = OwinRequest.Create();

            configure(request);
            return(new RequestInstance(request.Dictionary, _app));
        }
Beispiel #21
0
        public void CreateEnvironment()
        {
            var          creator     = typeof(Http11ProtocolOwinAdapter).GetMethod("CreateOwinEnvironment", BindingFlags.NonPublic | BindingFlags.Static);
            const string method      = "GET",
                         scheme      = "https",
                         host        = "localhost:80",
                         pathBase    = "",
                         path        = "/test.txt",
                         queryString = "xunit";

            var requestHeaders = new Dictionary <string, string[]> {
                { "Host", new[] { host } }
            };
            var environment = (Dictionary <string, object>)creator.Invoke(null, new object[] { method, scheme, pathBase, path, requestHeaders, queryString, null });

            var owinRequest = new OwinRequest(environment);

            Assert.Equal(owinRequest.Method, method);
            Assert.Equal(owinRequest.Scheme, scheme);
            Assert.Equal(owinRequest.PathBase.Value, pathBase);
            Assert.Equal(owinRequest.Path.Value, path);
            Assert.Equal(owinRequest.Body.Length, 0);
            Assert.Equal(owinRequest.Headers.ContainsKey("Host"), true);
            Assert.Equal(owinRequest.Headers["Host"], host);
            Assert.Equal(owinRequest.QueryString.Value, queryString);
            Assert.Equal(owinRequest.CallCancelled.IsCancellationRequested, false);

            var owinResponse = new OwinResponse(environment);

            Assert.Equal(owinResponse.Headers.Count, 0);
            Assert.Equal(owinResponse.Body.Length, 0);
            Assert.Equal(owinResponse.StatusCode, StatusCode.Code200Ok);
        }
Beispiel #22
0
        private RequestInstance BuildRequest(Action <IOwinRequest> configure)
        {
            IOwinRequest request = new OwinRequest();

            configure(request);
            return(new RequestInstance(request.Environment, _app));
        }
Beispiel #23
0
        private IEncoding SelectCompression(IDictionary <string, object> environment)
        {
            var request = new OwinRequest(environment);

            var bestAccept = new Accept {
                Encoding = "identity", Quality = 0
            };
            IEncoding bestEncoding = null;

            IList <string> acceptEncoding = request.Headers.GetValues("accept-encoding");

            if (acceptEncoding != null)
            {
                foreach (var segment in acceptEncoding)
                {
                    Accept accept = Parse(segment);
                    if (accept.Quality == 0 || accept.Quality < bestAccept.Quality)
                    {
                        continue;
                    }
                    IEncoding compression = _options.EncodingProvider.GetCompression(accept.Encoding);
                    if (compression == null)
                    {
                        continue;
                    }
                    bestAccept   = accept;
                    bestEncoding = compression;
                    if (accept.Quality == 1000)
                    {
                        break;
                    }
                }
            }
            return(bestEncoding);
        }
Beispiel #24
0
        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));
        }
        public void CallingMethodInvokesDelegate()
        {
            var res = new OwinResponse(OwinRequest.Create());

            res.CanSendFile.ShouldBe(false);

            string            aa = null;
            long              bb = 0;
            long?             cc = null;
            CancellationToken dd = CancellationToken.None;

            var cts = new CancellationTokenSource();

            res.SendFileAsyncDelegate = (a, b, c, d) =>
            {
                aa = a;
                bb = b;
                cc = c;
                dd = d;
                return(null);
            };
            res.SendFileAsync("one", 2, 3, cts.Token);
            aa.ShouldBe("one");
            bb.ShouldBe(2);
            cc.ShouldBe(3);
            dd.ShouldBe(cts.Token);

            res.SendFileAsync("four");
            aa.ShouldBe("four");
            bb.ShouldBe(0);
            cc.ShouldBe(null);
            dd.ShouldBe(CancellationToken.None);
        }
Beispiel #26
0
        public void When_request_user_is_not_defined_should_get_null()
        {
            var environment = new Dictionary <string, object>();
            var owinRequest = new OwinRequest(environment);

            owinRequest.User.Should().BeNull();
        }
Beispiel #27
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]);
        }
Beispiel #28
0
        public static RaygunRequestMessage Build(OwinEnvironment environment)
        {
            var request = new OwinRequest(environment);

            // ToDo: limit querystring, form, and header values to 256 characters
            var message = new RaygunRequestMessage();

            message.HostName   = request.Host.Value;
            message.Url        = request.Uri.AbsolutePath;
            message.HttpMethod = request.Method;
            message.IPAddress  = request.RemoteIpAddress; // ToDo: bring this up to par with the official client

            // ToDo: filter querystring values
            message.QueryString = request.Query.ToDictionary(_ => _.Key, _ => string.Join(", ", _.Value));

            // ToDo: filter form values (add 'password' by default?)
            message.Form = request.ReadForm().ToDictionary(_ => _.Key, _ => string.Join(", ", _.Value));

            // ToDo: filter headers
            message.Headers = request.Headers.ToDictionary(_ => _.Key, _ => string.Join(", ", _.Value));
            message.Headers.Remove("Cookie");

            message.Cookies = GetCookies(request.Cookies);

            if (request.ContentType != "text/html" && request.ContentType != "application/x-www-form-urlencoded" && request.Method != "GET")
            {
                var text = request.BodyAsString();

                message.RawData = text.Substring(0, Math.Min(4096, text.Length));
            }

            message.Data = GetData(request).Where(_ => _.Value != null).ToDictionary(_ => _.Key, _ => _.Value);

            return(message);
        }
Beispiel #29
0
        private static IEnumerable <KeyValuePair <string, object> > GetData(OwinRequest request)
        {
            #region OWIN v1.0.0 - 3.2.3. Other Data

            yield return(new KeyValuePair <string, object>(OwinConstants.OwinVersion, request.Get <string>(OwinConstants.OwinVersion)));

            #endregion

            #region OWIN v1.0.0 - 3.2.1. Request Data

            yield return(new KeyValuePair <string, object>(OwinConstants.RequestProtocol, request.Get <string>(OwinConstants.RequestProtocol)));

            #endregion

            #region OWIN Key Guidelines and Common Keys - 6. Common Keys

            var capabilities = request.Get <IDictionary <string, object> >(OwinConstants.CommonKeys.Capabilities);
            if (capabilities != null)
            {
                foreach (var capability in capabilities)
                {
                    yield return(capability);
                }
            }

            #endregion

            yield return(new KeyValuePair <string, object>("host.AppName", request.Get <string>("host.AppName")));

            yield return(new KeyValuePair <string, object>("host.AppMode", request.Get <string>("host.AppMode")));

            yield return(new KeyValuePair <string, object>("integratedpipeline.CurrentStage", request.Get <string>("integratedpipeline.CurrentStage")));
        }
Beispiel #30
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.SetHeader("Location", builder.ToString());
                response.StatusCode = 302;

                return(TaskAsyncHelper.Empty);
            }
            else
            {
                return(_next(env));
            }
        }
Beispiel #31
0
        private static AppFunc EnableAuthentication(AppFunc app, string password)
        {
            return(DigestAuthentication.Enable(
                       app,
                       (env) =>
            {
                var request = new OwinRequest(env);

                if (request.CanAccept)
                {
                    return false;
                }

                if (!request.Path.StartsWith("/backgrounds/"))
                {
                    return true;
                }

                if (request.Path.EndsWith("/list") || request.Path.EndsWith("/listall"))
                {
                    return true;
                }

                return false;                                 // all other requests to /backgrounds/ without /list(all)
            },
                       "WordsLive",
                       (user) => (user == "WordsLive" ?
                                  new DigestAuthentication.UserPassword {
                Password = password
            } :
                                  (DigestAuthentication.UserPassword?)null)
                       ));
        }
        public void ItStronglyTypesOwinKeys()
        {
            var headers = new Dictionary<string, string[]>(StringComparer.InvariantCultureIgnoreCase)
                {
                    {"alpha", new []{"beta", "gamma"}}
                };

            var body = new MemoryStream(new byte[] { 65, 66, 67, 68 });
            var cts = new CancellationTokenSource();
            var env = new Dictionary<string, object>(StringComparer.Ordinal)
                {
                    {"owin.RequestScheme", "http"},
                    {"owin.RequestMethod", "ONE"},
                    {"owin.RequestPathBase", "/two"},
                    {"owin.RequestPath", "/three"},
                    {"owin.RequestQueryString", "four=five"},
                    {"owin.RequestProtocol", "HTTP/1.0"},
                    {"owin.RequestHeaders", headers},
                    {"owin.RequestBody", body},
                    {"owin.Version", "1.0"},
                    {"owin.CallCancelled", cts.Token},
                };

            var req = new OwinRequest(env);
            req.Scheme.ShouldBe("http");
            req.Method.ShouldBe("ONE");
            req.PathBase.ShouldBe("/two");
            req.Path.ShouldBe("/three");
            req.QueryString.ShouldBe("four=five");
            req.Protocol.ShouldBe("HTTP/1.0");
            req.Headers.ShouldBeSameAs(headers);
            req.Body.ShouldBeSameAs(body);
            req.OwinVersion.ShouldBe("1.0");
            req.CallCancelled.ShouldBe(cts.Token);
        }
        public static Uri GetUri(OwinRequest request)
        {
            var queryString = request.QueryString;

            return string.IsNullOrWhiteSpace(queryString)
                ? new Uri(request.Scheme + "://" + GetHost(request) + request.PathBase + request.Path)
                : new Uri(request.Scheme + "://" + GetHost(request) + request.PathBase + request.Path + "?" + queryString);
        }
 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 static string GetHost(OwinRequest request)
        {
            var headers = request.Headers;

            var host = GetHeader(headers, "Host");
            if (!string.IsNullOrWhiteSpace(host))
            {
                return host;
            }

            var localIpAddress = request.LocalIpAddress ?? "localhost";
            var localPort = request.LocalPort;
            return string.IsNullOrWhiteSpace(localPort) ? localIpAddress : (localIpAddress + ":" + localPort);
        }
Beispiel #36
0
        public void ParseQuery()
        {
            IDictionary<string, object> environment = new Dictionary<string, object>();
            environment["owin.RequestQueryString"] = OriginalQueryString;
            IOwinRequest request = new OwinRequest(environment);
            Assert.Equal(OriginalQueryString, request.QueryString.Value);

            IReadableStringCollection query = request.Query;
            Assert.Equal("v1", query.Get("q1"));
            Assert.Equal("v2,b", query.Get("Q2"));
            Assert.Equal("v3,v4", query.Get("q3"));
            Assert.Null(query.Get("q4"));
            Assert.Equal("v5,v5", query.Get("Q5"));
        }
Beispiel #37
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);
        }
        public void ParseForm()
        {
            IDictionary<string, object> environment = new Dictionary<string, object>();
            environment["owin.RequestBody"] = new MemoryStream(Encoding.ASCII.GetBytes(OriginalFormsString));

            IOwinRequest request = new OwinRequest(environment);

            IFormCollection form = request.ReadFormAsync().Result;
            Assert.Equal("v1", form.Get("q1"));
            Assert.Equal("v2,b", form.Get("Q2"));
            Assert.Equal("v3,v4", form.Get("q3"));
            Assert.Null(form.Get("q4"));
            Assert.Equal("v5,v5", form.Get("Q5"));
        }
        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);

                        response.Authentication.SignIn(identity);

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

                    return;
                }
            }

            await _next(env);
        }
 public void ReadFromStream()
 {
     var stream = new MemoryStream();
     var writer = new StreamWriter(stream);
     writer.Write(OriginalFormsString);
     writer.Flush();
     stream.Seek(0, SeekOrigin.Begin);
     IOwinRequest request = new OwinRequest();
     request.Body = stream;
     IFormCollection form = request.ReadFormAsync().Result;
     Assert.Equal("v1", form.Get("q1"));
     Assert.Equal("v2,b", form.Get("Q2"));
     Assert.Equal("v3,v4", form.Get("q3"));
     Assert.Null(form.Get("q4"));
     Assert.Equal("v5,v5", form.Get("Q5"));
 }
        public static string GetMethodOverride(OwinRequest request)
        {
            var method = request.Method;
            if (!string.Equals("POST", method, StringComparison.OrdinalIgnoreCase))
            {
                // override has no effect on POST
                return method;
            }

            var methodOverride = GetHeader(request.Headers, "X-Http-Method-Override");
            if (string.IsNullOrEmpty(methodOverride))
            {
                return method;
            }

            return methodOverride;
        }
        /// <summary>
        ///     Limits the number of concurrent requests that can be handled used by the subsequent stages in the owin pipeline.
        /// </summary>
        /// <param name="getMaxConcurrentRequests">
        ///     A delegate to retrieve the maximum number of concurrent requests. Allows you
        ///     to supply different values at runtime. Use 0 or a negative number to specify unlimited number of concurrent
        ///     requests.
        /// </param>
        /// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
        /// <returns>An OWIN middleware delegate.</returns>
        /// <exception cref="System.ArgumentNullException">getMaxConcurrentRequests</exception>
        public static MidFunc MaxConcurrentRequests(
            Func<RequestContext, int> getMaxConcurrentRequests,
            string loggerName = null)
        {
            getMaxConcurrentRequests.MustNotNull("getMaxConcurrentRequests");

            loggerName = string.IsNullOrWhiteSpace(loggerName)
                ? "LimitsMiddleware.MaxConcurrentRequests"
                : loggerName;
            var logger = LogProvider.GetLogger(loggerName);
            var concurrentRequestCounter = 0;

            return
                next =>
                async env =>
                {
                    var owinRequest = new OwinRequest(env);
                    var limitsRequestContext = new RequestContext(owinRequest);
                    int maxConcurrentRequests = getMaxConcurrentRequests(limitsRequestContext);
                    if (maxConcurrentRequests <= 0)
                    {
                        maxConcurrentRequests = int.MaxValue;
                    }
                    try
                    {
                        int concurrentRequests = Interlocked.Increment(ref concurrentRequestCounter);
                        logger.Debug("Concurrent request {0}/{1}.".FormatWith(concurrentRequests, maxConcurrentRequests));
                        if (concurrentRequests > maxConcurrentRequests)
                        {
                            logger.Info("Limit ({0}). Request rejected."
                                .FormatWith(maxConcurrentRequests, concurrentRequests));
                            var response = new OwinContext(env).Response;
                            response.StatusCode = 503;
                            response.ReasonPhrase = "Service Unavailable";
                            response.Write(response.ReasonPhrase);
                            return;
                        }
                        await next(env);
                    }
                    finally
                    {
                        int concurrentRequests = Interlocked.Decrement(ref concurrentRequestCounter);
                        logger.Debug("Concurrent request {0}/{1}.".FormatWith(concurrentRequests, maxConcurrentRequests));
                    }
                };
        }
    public static IDictionary<string, string> GetCookies(OwinRequest request)
    {
        var cookies = request.Get<IDictionary<string, string>>("Owin.Types.Cookies#dictionary");
            if (cookies == null)
            {
                cookies = new Dictionary<string, string>(StringComparer.Ordinal);
                request.Set("Owin.Types.Cookies#dictionary", cookies);
            }

            var text = request.GetHeader("Cookie");
            if (request.Get<string>("Owin.Types.Cookies#text") != text)
            {
                cookies.Clear();
                ParseDelimited(text, SemicolonAndComma, AddCookieCallback, cookies);
                request.Set("Owin.Types.Cookies#text", text);
            }
            return cookies;
    }
        public static string GetForwardedHost(OwinRequest request)
        {
            var headers = request.Headers;

            var forwardedHost = GetHeaderSplit(headers, "X-Forwarded-Host");
            if (forwardedHost != null)
            {
                return forwardedHost.Last();
            }

            var host = GetHeader(headers, "Host");
            if (!string.IsNullOrWhiteSpace(host))
            {
                return host;
            }

            var localIpAddress = request.LocalIpAddress ?? "localhost";
            var localPort = request.LocalPort;
            return string.IsNullOrWhiteSpace(localPort) ? localIpAddress : (localIpAddress + ":" + localPort);
        }
Beispiel #45
0
        protected async Task BaseInitialize(AuthenticationOptions options, OwinRequest request, OwinResponse response)
        {
            _baseOptions = options;
            Request = request;
            Response = response;
            Helper = new SecurityHelper(request);
            RequestPathBase = Request.PathBase;

            _registration = Request.RegisterAuthenticationHandler(this);

            Request.OnSendingHeaders(state => ((AuthenticationHandler)state).ApplyResponse().Wait(), this);

            await InitializeCore();

            if (BaseOptions.AuthenticationMode == AuthenticationMode.Active)
            {
                AuthenticationTicket ticket = await Authenticate();
                if (ticket != null && ticket.Identity != null)
                {
                    Helper.AddUserIdentity(ticket.Identity);
                }
            }
        }
        public async Task Invoke(IDictionary<string, object> env)
        {
            var req = new OwinRequest(env);
            string file;
            if (!_router.TryGet(req.Path, out file))
            {
                await _next(env);
            }

            var resp = new OwinResponse(req)
            {
                ContentType = "text/html"
            };

            if (!File.Exists(file))
            {
                resp.StatusCode = 404;
                await resp.WriteAsync("File not found");
            }
            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                await fs.CopyToAsync(resp.Body);
            }
        }
 public static OwinRequest ApplyForwardedUri(OwinRequest request)
 {
     return ApplyForwardedHost(ApplyForwardedScheme(request));
 }
        private IOwinRequest CreateRequest(string url)
        {
            var uriBuilder = new UriBuilder(url);
            var request = new OwinRequest();
            request.Path = PathString.FromUriComponent(uriBuilder.Uri);
            request.PathBase = PathString.Empty;
            request.Scheme = uriBuilder.Scheme;
            request.QueryString = QueryString.FromUriComponent(uriBuilder.Uri);

            return request;
        }
 private RequestInstance BuildRequest(Action<IOwinRequest> configure)
 {
     IOwinRequest request = new OwinRequest();
     configure(request);
     return new RequestInstance(request.Environment, _app);
 }
 public static OwinRequest ApplyForwardedHost(OwinRequest request)
 {
     request.Host = GetForwardedHost(request);
     return request;
 }
 public static OwinRequest ApplyForwardedScheme(OwinRequest request)
 {
     request.Scheme = GetForwardedScheme(request);
     return request;
 }
 public static OwinRequest ApplyMethodOverride(OwinRequest request)
 {
     request.Method = GetMethodOverride(request);
     return request;
 }
 /// <summary>
 /// Helper code used when implementing authentication middleware
 /// </summary>
 /// <param name="environment"></param>
 public SecurityHelper(IDictionary<string, object> environment)
 {
     _request = new OwinRequest(environment);
     _response = new OwinResponse(environment);
 }
Beispiel #54
0
 /// <summary>
 /// Helper code used when implementing authentication middleware
 /// </summary>
 /// <param name="request"></param>
 public SecurityHelper(OwinRequest request)
 {
     _request = request;
     _response = new OwinResponse(request);
 }
        private IEncoding SelectCompression(IDictionary<string, object> environment)
        {
            var request = new OwinRequest(environment);

            var bestAccept = new Accept { Encoding = "identity", Quality = 0 };
            IEncoding bestEncoding = null;

            IList<string> acceptEncoding = request.Headers.GetValues("accept-encoding");
            if (acceptEncoding != null)
            {
                foreach (var segment in acceptEncoding)
                {
                    Accept accept = Parse(segment);
                    if (accept.Quality == 0 || accept.Quality < bestAccept.Quality)
                    {
                        continue;
                    }
                    IEncoding compression = _options.EncodingProvider.GetCompression(accept.Encoding);
                    if (compression == null)
                    {
                        continue;
                    }
                    bestAccept = accept;
                    bestEncoding = compression;
                    if (accept.Quality == 1000)
                    {
                        break;
                    }
                }
            }
            return bestEncoding;
        }
Beispiel #56
0
 public AuthenticationManager(OwinRequest request)
 {
     _request = request;
     _response = new OwinResponse(request);
 }
        public void SettersModifyEnvironment()
        {
            var headers = new Dictionary<string, string[]>(StringComparer.InvariantCultureIgnoreCase)
                {
                    { "alpha", new[] { "beta", "gamma" } }
                };
            var body = new MemoryStream(new byte[] { 65, 66, 67, 68 });
            var cts = new CancellationTokenSource();

            var env = new Dictionary<string, object>(StringComparer.Ordinal);
            var req = new OwinRequest(env)
                {
                    Scheme = "http",
                    Method = "ONE",
                    PathBase = "/two",
                    Path = "/three",
                    QueryString = "four=five",
                    Protocol = "HTTP/1.0",
                    Headers = headers,
                    Body = body,
                    OwinVersion = "1.0",
                    CallCancelled = cts.Token
                };
            env["owin.RequestScheme"].ShouldBe("http");
            env["owin.RequestMethod"].ShouldBe("ONE");
            env["owin.RequestPathBase"].ShouldBe("/two");
            env["owin.RequestPath"].ShouldBe("/three");
            env["owin.RequestQueryString"].ShouldBe("four=five");
            env["owin.RequestProtocol"].ShouldBe("HTTP/1.0");
            env["owin.RequestHeaders"].ShouldBe(headers);
            env["owin.RequestBody"].ShouldBe(body);
            env["owin.Version"].ShouldBe("1.0");
            env["owin.CallCancelled"].ShouldBe(cts.Token);
        }
 public OwinResponse(OwinRequest request)
 {
     _dictionary = request.Dictionary;
 }
 private async Task OnHandler3(OwinRequest request, OwinResponse response, Func<Task> next)
 {
     await next();
 }
Beispiel #60
0
 public override Task Invoke(OwinRequest request, OwinResponse response)
 {
     return _next(request.Environment);
 }