예제 #1
0
        internal static IDictionary <string, string[]> GetQuery(OwinRequest request)
        {
            var query = request.Get <IDictionary <string, string[]> >("Microsoft.Owin.Query#dictionary");

            if (query == null)
            {
                query = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase);
                request.Set("Microsoft.Owin.Query#dictionary", query);
            }

            string text = request.QueryString.Value;

            if (request.Get <string>("Microsoft.Owin.Query#text") != text)
            {
                query.Clear();
                var accumulator = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase);
                ParseDelimited(text, AmpersandAndSemicolon, AppendItemCallback, accumulator);
                foreach (var kv in accumulator)
                {
                    query.Add(kv.Key, kv.Value.ToArray());
                }
                request.Set("Microsoft.Owin.Query#text", text);
            }
            return(query);
        }
예제 #2
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")));
        }
예제 #3
0
		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);
			};
		}
예제 #4
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);
        }
예제 #5
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
            });
        }
예제 #6
0
        public static object RegisterAuthenticationHandler(this OwinRequest request, AuthenticationHandler handler)
        {
            var chained = request.Get <AuthenticateDelegate>(Constants.SecurityAuthenticate);
            var hook    = new Hook(handler, chained);

            request.Set <AuthenticateDelegate>(Constants.SecurityAuthenticate, hook.Authenticate);
            return(hook);
        }
    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;
    }
예제 #8
0
        public Task Invoke(IDictionary <string, object> env)
        {
            var request  = new OwinRequest(env);
            var response = new OwinResponse(env);

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

            var    cookies = request.GetCookies();
            string cookieValue;

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

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

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

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

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

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

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

            return(_next(env));
        }
        public static IDictionary <string, string[]> GetQuery(OwinRequest request)
        {
            var query = request.Get <IDictionary <string, string[]> >("Owin.Types.Query#dictionary");

            if (query == null)
            {
                query = new Dictionary <string, string[]>(StringComparer.Ordinal);
                request.Set("Owin.Types.Query#dictionary", query);
            }

            var text = request.QueryString;

            if (request.Get <string>("Owin.Types.Query#text") != text)
            {
                query.Clear();
                ParseDelimited(text, AmpersandAndSemicolon, AddQueryCallback, query);
                request.Set("Owin.Types.Query#text", text);
            }
            return(query);
        }
예제 #10
0
        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);
        }
예제 #11
0
        public static void SetHeader(this OwinRequest request, string name, string[] values)
        {
            var headers = request.Get <IDictionary <string, string[]> >("owin.RequestHeaders");

            if (headers == null)
            {
                headers = new Dictionary <string, string[]>();
                request.Set <IDictionary <string, string[]> >("owin.RequestHeaders", headers);
            }

            headers.Add(name, values);
        }
예제 #12
0
        public static bool IsAuthenticationMethodEnabled(OwinRequest request, string authenticationMethod)
        {
            IEnumerable <string> authenticationMethods = request.Get <IEnumerable <string> >(
                AuthenticationKeys.AuthenticationMethods);

            if (authenticationMethods != null && !authenticationMethods.Any(m => String.Equals(authenticationMethod, m,
                                                                                               StringComparison.OrdinalIgnoreCase)))
            {
                return(false);
            }

            return(true);
        }
예제 #13
0
        internal static string GetHost(OwinRequest request)
        {
            var headers = request.Headers;

            string host = GetHeader(headers, "Host");

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

            string localIpAddress = request.LocalIpAddress ?? "localhost";
            var    localPort      = request.Get <string>(OwinConstants.CommonKeys.LocalPort);

            return(string.IsNullOrWhiteSpace(localPort) ? localIpAddress : (localIpAddress + ":" + localPort));
        }
예제 #14
0
 private static Action <Action <object>, object> GetRegisterOnSendingHeaders(OwinRequest request)
 {
     return(request.Get <Action <Action <object>, object> >(OwinConstants.CommonKeys.OnSendingHeaders));
 }