public void Save(NancyContext context)
        {
            var session = context.Request.Session;

            if (session == null || !session.HasChanged)
            {
                return;
            }

            var sessionId = SessionIdFromCookie(context);

            if (String.IsNullOrEmpty(sessionId))
            {
                sessionId = NewSessionId();
                var cookie = new NancyCookie(CookieName, sessionId, true);
                context.Response.AddCookie(cookie);
            }

            var dict = new Dictionary <string, object>(session.Count);

            foreach (var kvp in session)
            {
                dict.Add(kvp.Key, kvp.Value);
            }
            SaveToStore(sessionId, dict);
        }
        public void Save(NancyContext context)
        {
            var session = context.Request.Session;

            if (session == null || !session.HasChanged)
            {
                return;
            }

            var token = MemcacheTokenFromCookie(context);

            if (string.IsNullOrEmpty(token))
            {
                var sessionId = NewSessionId();
                var cookie    = new NancyCookie(CookieName, sessionId, true);
                context.Response.Cookies.Add(cookie);
                token = string.Concat(MemcachePrefix, sessionId);
            }

            var dictionary = new Dictionary <string, object>(session.Count);

            foreach (var kvp in session)
            {
                dictionary.Add(kvp.Key, kvp.Value);
            }
            SaveToMemcache(token, dictionary);
        }
Beispiel #3
0
        /// <summary>
        /// Logs out the user by expiring authentication token cookie
        /// </summary>
        /// <param name="context"></param>
        public static void LogOut(this NancyContext context)
        {
            var cookie = new NancyCookie(RegistrationConfiguration.AuthenticationCookieName, null);

            cookie.Expires = System.DateTime.MinValue;
            context.Response.WithCookie(cookie);
        }
Beispiel #4
0
        /// <summary>
        /// Save the session into the response
        /// </summary>
        /// <param name="session">Session to save</param>
        /// <param name="response">Response to save into</param>
        public void Save(ISession session, Response response)
        {
            if (session == null || !session.HasChanged)
            {
                return;
            }

            var sb = new StringBuilder();

            foreach (var kvp in session)
            {
                sb.Append(HttpUtility.UrlEncode(kvp.Key));
                sb.Append("=");

                var objectString = this.serializer.Serialize(kvp.Value);

                sb.Append(HttpUtility.UrlEncode(objectString));
                sb.Append(";");
            }

            // TODO - configurable path?
            var encryptedData = this.encryptionProvider.Encrypt(sb.ToString());
            var hmacBytes     = this.hmacProvider.GenerateHmac(encryptedData);
            var cookieData    = String.Format("{0}{1}", Convert.ToBase64String(hmacBytes), encryptedData);

            var cookie = new NancyCookie(cookieName, cookieData, true);

            response.AddCookie(cookie);
        }
Beispiel #5
0
        public Task Invoke(IDictionary <string, object> environment)
        {
            var requestHeaders = ((IDictionary <string, string[]>)environment["owin.RequestHeaders"]);

            if (!requestHeaders.ContainsKey("Cookie"))
            {
                return(_next.Invoke(environment));
            }
            NancyCookie authCookie = GetFormsAuthCookies(requestHeaders["Cookie"]).SingleOrDefault();

            if (authCookie == null)
            {
                return(_next.Invoke(environment));
            }
            string user = FormsAuthentication.DecryptAndValidateAuthenticationCookie(authCookie.Value, _formsAuthenticationConfiguration);
            Guid   userId;

            if (Guid.TryParse(user, out userId))
            {
                ClaimsPrincipal claimsPrincipal = _userManager.GetClaimsPrincial(Guid.Parse(userId));
                if (environment.ContainsKey(ServerUser))
                {
                    environment[ServerUser] = claimsPrincipal;
                }
                else
                {
                    environment.Add(ServerUser, claimsPrincipal);
                }
            }
            return(_next.Invoke(environment));
        }
        /// <summary>
        /// Save the session into the response
        /// </summary>
        /// <param name="session">Session to save</param>
        /// <param name="response">Response to save into</param>
        public void Save(ISession session, Nancy.Response response)
        {
            this.ExpireOldSessions();

            if (session == null || !session.HasChanged)
            {
                return;
            }

            var id = session["_id"] as string;

            if (null == id)
            {
                // TODO: warn
                return;
            }

            // Persist the session
            session.Delete("_id");
            Await(RethinkDbSessionStore.UpdateSession(currentConfiguration, id, session));

            // Encrypt the session Id in the cookie
            var cryptographyConfiguration = this.currentConfiguration.CryptographyConfiguration;
            var encryptedData             = cryptographyConfiguration.EncryptionProvider.Encrypt(id);
            var hmacBytes  = cryptographyConfiguration.HmacProvider.GenerateHmac(encryptedData);
            var cookieData = HttpUtility.UrlEncode(String.Format("{0}{1}", Convert.ToBase64String(hmacBytes), encryptedData));

            var cookie = new NancyCookie(this.currentConfiguration.CookieName, cookieData, true)
            {
                Domain = this.currentConfiguration.Domain,
                Path   = this.currentConfiguration.Path
            };

            response.WithCookie(cookie);
        }
Beispiel #7
0
        private void SlidingAuthenticationForFormsAuth(NancyContext context)
        {
            if (context.CurrentUser == null)
            {
                return;
            }

            var formsAuthCookieName = FormsAuthentication.FormsAuthenticationCookieName;

            if (!context.Request.Path.Equals("/logout") &&
                context.Request.Cookies.ContainsKey(formsAuthCookieName))
            {
                var formsAuthCookieValue = context.Request.Cookies[formsAuthCookieName];

                if (FormsAuthentication.DecryptAndValidateAuthenticationCookie(formsAuthCookieValue, FormsAuthConfig).IsNotNullOrWhiteSpace())
                {
                    var formsAuthCookie = new NancyCookie(formsAuthCookieName, formsAuthCookieValue, true, false, DateTime.UtcNow.AddDays(7))
                    {
                        Path = GetCookiePath()
                    };

                    context.Response.WithCookie(formsAuthCookie);
                }
            }
        }
Beispiel #8
0
        public CookieModule()
        {
            Get["/setcookie"] = _ =>
            {
                const string value = "HakLqr1OEdi+kQ/s92Rzz9hV1w/vzGZKqWeMQRHRJlwhbbgP87UELJZlYDfbVVLo";

                var cookie = new NancyCookie("testcookie", value);

                var response = new Response();
                response.WithCookie(cookie);
                response.StatusCode = HttpStatusCode.OK;

                return(response);
            };

            Get["/getcookie"] = _ =>
            {
                const string value = "HakLqr1OEdi+kQ/s92Rzz9hV1w/vzGZKqWeMQRHRJlwhbbgP87UELJZlYDfbVVLo";

                var cookie = Context.Request.Cookies["testcookie"];

                return(String.Equals(cookie, value) ?
                       HttpStatusCode.OK :
                       HttpStatusCode.InternalServerError);
            };
        }
Beispiel #9
0
        public void Should_set_negotiated_cookies_to_response()
        {
            // Given
            var negotiatedCookie =
                new NancyCookie("test", "test");

            var browser = new Browser(with =>
            {
                with.ResponseProcessor <TestProcessor>();

                with.Module(new ConfigurableNancyModule(x =>
                {
                    x.Get("/", CreateNegotiatedResponse(config =>
                    {
                        config.WithCookie(negotiatedCookie);
                    }));
                }));
            });

            // When
            var response = browser.Get("/", with =>
            {
                with.Accept("test/test", 0.9m);
            });

            // Then
            Assert.Same(negotiatedCookie, response.Cookies.First());
        }
Beispiel #10
0
        /// <summary>
        /// Save the session into the response
        /// </summary>
        /// <param name="session">Session to save</param>
        /// <param name="response">Response to save into</param>
        public void Save(ISession session, Response response)
        {
            if (session == null || !session.HasChanged)
            {
                return;
            }

            var sb = new StringBuilder();

            foreach (var kvp in session)
            {
                sb.Append(HttpUtility.UrlEncode(kvp.Key));
                sb.Append("=");

                var objectString = this.currentConfiguration.Serializer.Serialize(kvp.Value);

                sb.Append(HttpUtility.UrlEncode(objectString));
                sb.Append(";");
            }

            var cryptographyConfiguration = this.currentConfiguration.CryptographyConfiguration;
            var encryptedData             = cryptographyConfiguration.EncryptionProvider.Encrypt(sb.ToString());
            var hmacBytes  = cryptographyConfiguration.HmacProvider.GenerateHmac(encryptedData);
            var cookieData = HttpUtility.UrlEncode(String.Format("{0}{1}", Convert.ToBase64String(hmacBytes), encryptedData));

            var cookie = new NancyCookie(this.currentConfiguration.CookieName, cookieData, true)
            {
                Domain = this.currentConfiguration.Domain,
                Path   = this.currentConfiguration.Path
            };

            response.WithCookie(cookie);
        }
Beispiel #11
0
        public Response Logout(string baseUri)
        {
            // Reset the token to an empty string and set an very old expiration date
            var cookie = new NancyCookie(_authSettings.CookieName, String.Empty, DateTime.MinValue);

            return(Response.AsRedirect(baseUri).WithCookie(cookie));
        }
        public void Should_encode_value_if_necessary()
        {
            var cookie = new NancyCookie("Test", "Value with spaces");

            var result = cookie.EncodedValue;

            result.ShouldEqual("Value+with+spaces");
        }
        public void Should_encode_key_if_necessary()
        {
            var cookie = new NancyCookie("with spaces", "Value");

            var result = cookie.EncodedName;

            result.ShouldEqual("with+spaces");
        }
        public void Should_encode_key_and_value_when_stringified()
        {
            var cookie = new NancyCookie("Key with spaces", "Value with spaces");

            var result = cookie.ToString();

            result.ShouldEqual("Key+with+spaces=Value+with+spaces; path=/");
        }
        public void Should_add_http_only_if_set_to_true()
        {
            var cookie = new NancyCookie("Test", "Value", true);

            var result = cookie.ToString();

            result.ShouldContain("HttpOnly");
        }
        public void Should_add_secure_if_set_to_true()
        {
            var cookie = new NancyCookie("Test", "Value", true, true);

            var result = cookie.ToString();

            result.ShouldContain("Secure");
        }
        public void Should_not_add_secure_if_set_to_false()
        {
            var cookie = new NancyCookie("Test", "Value", false, false);

            var result = cookie.ToString();

            result.ShouldNotContain("Secure");
        }
Beispiel #18
0
        public void Should_encode_key_and_value_when_stringified()
        {
            var cookie = new NancyCookie("Key with spaces", "Value with spaces");

            var result = cookie.ToString();

            result.ShouldEqual("Key+with+spaces=Value+with+spaces; path=/");
        }
Beispiel #19
0
        public void Should_encode_key_if_necessary()
        {
            var cookie = new NancyCookie("with spaces", "Value");

            var result = cookie.EncodedName;

            result.ShouldEqual("with+spaces");
        }
Beispiel #20
0
        public void Should_add_secure_if_set_to_true()
        {
            var cookie = new NancyCookie("Test", "Value", true, true);

            var result = cookie.ToString();

            result.ShouldContain("Secure");
        }
Beispiel #21
0
        public void Should_encode_value_if_necessary()
        {
            var cookie = new NancyCookie("Test", "Value with spaces");

            var result = cookie.EncodedValue;

            result.ShouldEqual("Value+with+spaces");
        }
Beispiel #22
0
        public void Should_not_add_http_only_if_set_to_false()
        {
            var cookie = new NancyCookie("Test", "Value", false);

            var result = cookie.ToString();

            result.ShouldNotContain("HttpOnly");
        }
Beispiel #23
0
        private void UpdateTraceCookie(NancyContext ctx, Guid sessionGuid)
        {
            var cookie = new NancyCookie("__NCTRACE", sessionGuid.ToString(), true)
            {
                Expires = DateTime.Now.AddMinutes(30)
            };

            ctx.Response.AddCookie(cookie);
        }
Beispiel #24
0
        /// <summary>
        /// Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime?cookieExpiry, FormsAuthenticationConfiguration configuration)
        {
            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);

            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL)
            {
                Expires = cookieExpiry
            };

            return(cookie);
        }
Beispiel #25
0
        public void Should_stringify_a_domain()
        {
            // Given
            var cookie = new NancyCookie("leto", "worm") { Domain = "google.com" };

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual("leto=worm; path=/; domain=google.com");
        }
        public void Should_stringify_a_simple_name_value()
        {
            // Given
            var cookie = new NancyCookie("leto", "worm");

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual("leto=worm; path=/");
        }
Beispiel #27
0
        public void Should_stringify_an_expiry_to_gmt_and_stupid_format()
        {
            // Given
            var date = new DateTime(2015, 10, 8, 9, 10, 11, DateTimeKind.Utc);

            // When
            var cookie = new NancyCookie("leto", "worm") { Expires = date }.ToString();

            // Then
            cookie.ShouldEqual("leto=worm; path=/; expires=Thu, 08-Oct-2015 09:10:11 GMT");
        }
Beispiel #28
0
        public void Should_stringify_a_path()
        {
            // Given
            var cookie = new NancyCookie("leto", "worm") { Path = "/nancy" };

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual("leto=worm; path=/nancy");
        }
Beispiel #29
0
        public void Should_stringify_a_simple_name_value()
        {
            // Given
            var cookie = new NancyCookie("leto", "worm");

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual("leto=worm; path=/");
        }
 public LogoutModule(IRootPathProvider pathProvider)
 {
     Get["/logout"] = _ =>
     {
         //delete cookie, http only with encrypted username and add it to the current response
         var mc = new NancyCookie("flex", "", true);
         mc.Expires = DateTime.Now.Subtract(new TimeSpan(100000)); //deletes the cookie
         var res = Response.AsRedirect("/");
         res.WithCookie(mc);
         return(res);
     };
 }
        private static void AddAuthenticationCookie(this Response response,
                                                    IAuthenticationTokenService authenticationTokenService,
                                                    ChatUser user)
        {
            string userToken = authenticationTokenService.GetAuthenticationToken(user);
            var    cookie    = new NancyCookie(Constants.UserTokenCookie, userToken, httpOnly: true)
            {
                Expires = DateTime.Now + TimeSpan.FromDays(30)
            };

            response.AddCookie(cookie);
        }
        public void Should_stringify_an_expiry_to_gmt_and_stupid_format()
        {
            // Given
            var date = new DateTime(2015, 10, 8, 9, 10, 11, DateTimeKind.Utc);

            // When
            var cookie = new NancyCookie("leto", "worm")
            {
                Expires = date
            }.ToString();

            // Then
            cookie.ShouldEqual("leto=worm; path=/; expires=Thu, 08-Oct-2015 09:10:11 GMT");
        }
        public void Should_stringify_a_domain()
        {
            // Given
            var cookie = new NancyCookie("leto", "worm")
            {
                Domain = "google.com"
            };

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual("leto=worm; path=/; domain=google.com");
        }
        public void Should_stringify_a_path()
        {
            // Given
            var cookie = new NancyCookie("leto", "worm")
            {
                Path = "/nancy"
            };

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual("leto=worm; path=/nancy");
        }
Beispiel #35
0
        /// <summary>
        /// Builds a cookie for logging a user out
        /// </summary>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration)
        {
            var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1));

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return(cookie);
        }
        public void Should_stringify_everyting()
        {
            // Given
            var date     = new DateTime(2016, 11, 8, 9, 10, 11, DateTimeKind.Utc);
            var tuesday  = GetInvariantAbbreviatedWeekdayName(date);
            var november = GetInvariantAbbreviatedMonthName(date);
            var cookie   = new NancyCookie("paul", "blind", true, true)
            {
                Expires = date, Path = "/frank", Domain = "gmail.com"
            };

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual(string.Format("paul=blind; path=/frank; expires={0}, 08-{1}-2016 09:10:11 GMT; domain=gmail.com; Secure; HttpOnly", tuesday, november));
        }
Beispiel #37
0
        private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
        {
            if (context.Response == null)
            {
                return;
            }

            session.Expiry = DateTime.Now.AddMinutes(DiagnosticsSessionTimeoutMinutes);
            var serializedSession = serializer.Serialize(session);

            var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession);
            var hmacBytes        = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
            var hmacString       = Convert.ToBase64String(hmacBytes);

            var cookie = new NancyCookie(DiagsCookieName, String.Format("{1}{0}", encryptedSession, hmacString), true);

            context.Response.AddCookie(cookie);
        }
Beispiel #38
0
        /// <summary>
        /// Sets a cookie representing an Authentication token object. Depending on the Registration Configuration,
        /// this method will set the expiration accordingly
        /// </summary>
        /// <param name="context"></param>
        /// <param name="account"></param>
        public static void SetAuthenticationToken(this NancyContext context, Account account)
        {
            var expiration = RegistrationConfiguration.CreatePersistantCookie
                ? System.DateTime.UtcNow.AddYears(1)
                : System.DateTime.UtcNow.AddMinutes(RegistrationConfiguration.ExpirationMinutes);
            var token = new AuthenticationToken
            {
                UserName     = account.Username,
                UserId       = account.Id,
                ExpiresOnUtc = expiration
            };
            var serialized = JsonConvert.SerializeObject(token);
            var encrypted  = serialized.EncryptText();

            var cookie = new NancyCookie(RegistrationConfiguration.AuthenticationCookieName, encrypted);

            context.Response.WithCookie(cookie);
        }
Beispiel #39
0
        /// <summary>
        /// Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime?cookieExpiry, FormsAuthenticationConfiguration configuration)
        {
            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);

            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry);

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return(cookie);
        }
Beispiel #40
0
        public void Should_stringify_an_expiry_to_english()
        {
            var originalCulture = System.Threading.Thread.CurrentThread.CurrentCulture;
            try
            {
                // Given
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");
                var date = new DateTime(2015, 10, 8, 9, 10, 11, DateTimeKind.Utc);

                // When
                var cookie = new NancyCookie("leto", "worm") { Expires = date }.ToString();

                // Then
                cookie.ShouldEqual("leto=worm; path=/; expires=Thu, 08-Oct-2015 09:10:11 GMT");
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = originalCulture;
            }
        }
Beispiel #41
0
        private static void AddUpdateSessionCookie(DiagnosticsSession session, NancyContext context, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer)
        {
            if (context.Response == null)
            {
                return;
            }

            session.Expiry = DateTime.Now.AddMinutes(diagnosticsConfiguration.SlidingTimeout);
            var serializedSession = serializer.Serialize(session);

            var encryptedSession = diagnosticsConfiguration.CryptographyConfiguration.EncryptionProvider.Encrypt(serializedSession);
            var hmacBytes = diagnosticsConfiguration.CryptographyConfiguration.HmacProvider.GenerateHmac(encryptedSession);
            var hmacString = Convert.ToBase64String(hmacBytes);

            var cookie = new NancyCookie(diagnosticsConfiguration.CookieName, String.Format("{1}{0}", encryptedSession, hmacString), true);

            context.Response.AddCookie(cookie);
        }
        /// <summary>
        /// Save the session into the response
        /// </summary>
        /// <param name="session">Session to save</param>
        /// <param name="response">Response to save into</param>
        public void Save(ISession session, Response response)
        {
            Guid sessionId;

            if (session == null || !session.HasChanged)
            {
                return;
            }

            if (session["__SessionId"] is Guid)
            {
                sessionId = (Guid)session["__SessionId"];
            }
            else
            {
                sessionId = Guid.NewGuid();
                session["__SessionId"] = sessionId;
                if (_currentConfiguration.SessionDuration != 0)
                    session["__SessionExpiration"] = DateTime.Now.AddSeconds(_currentConfiguration.SessionDuration);
            }

            var sb = new StringBuilder();
            foreach (var kvp in session)
            {
                sb.Append(HttpUtility.UrlEncode(kvp.Key));
                sb.Append("=");

                var objectString = _currentConfiguration.Serializer.Serialize(kvp.Value);

                sb.Append(HttpUtility.UrlEncode(objectString));
                sb.Append(";");
            }

            var cryptographyConfiguration = _currentConfiguration.CryptographyConfiguration;

            var redisData = cryptographyConfiguration.EncryptionProvider.Encrypt(sb.ToString());

            // Store the value in Redis
            _db.StringSet(_currentConfiguration.Prefix + sessionId.ToString(), redisData);

            if (_currentConfiguration.SessionDuration != 0)
                _db.KeyExpire(_currentConfiguration.Prefix + sessionId.ToString(), TimeSpan.FromSeconds(_currentConfiguration.SessionDuration));

            var encryptedSessionId = cryptographyConfiguration.EncryptionProvider.Encrypt(sessionId.ToString());
            var hmacBytes = cryptographyConfiguration.HmacProvider.GenerateHmac(sessionId.ToString());
            var cookieData = String.Format("{0}{1}", Convert.ToBase64String(hmacBytes), encryptedSessionId);

            var cookie = new NancyCookie(_currentConfiguration.CookieName, cookieData, true)
            {
                Domain = _currentConfiguration.Domain,
                Path = _currentConfiguration.Path
            };

            if (_currentConfiguration.EnableSlidingSessions)
                session["__SessionExpiration"] = DateTime.Now.AddSeconds(_currentConfiguration.SessionDuration);

            if (session["__SessionExpiration"] is DateTime)
                cookie.Expires = (DateTime)session["__SessionExpiration"];

            response.WithCookie(cookie);
        }
        private static Action<NancyContext> GetUpdateSessionCookieHook(FormsAuthenticationConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            return context =>
                {
                    var userHasLoggedOut = context.Items.ContainsKey(UserLoggedOutKey);

                    var shouldCopyExistingCookie = context.Request.Cookies.ContainsKey(FormsAuthenticationCookieName)
                                                   && !userHasLoggedOut 
                                                   && context.CurrentUser != null;

                    if (shouldCopyExistingCookie)
                    {
                        var formsAuthCookieValue = context.Request.Cookies[FormsAuthenticationCookieName];

                        var expires = DateTime.UtcNow.AddMinutes(configuration.SlidingSessionExpirationMinutes);

                        var newCookie = new NancyCookie(
                            FormsAuthenticationCookieName,
                            formsAuthCookieValue,
                            true,
                            configuration.RequiresSSL,
                            expires);

                        context.Response.WithCookie(newCookie);

                        // Also update the cache entry to keep consistent
                        configuration.AuthSessionIdStore.Extend((Guid)context.Items[AuthSessionIdItemKey], expires);
                    }
                };
        }
        public void Should_set_negotiated_cookies_to_response()
        {
            // Given
            var negotiatedCookie =
                new NancyCookie("test", "test");

            var browser = new Browser(with =>
            {
                with.ResponseProcessor<TestProcessor>();

                with.Module(new ConfigurableNancyModule(x =>
                {
                    x.Get("/", CreateNegotiatedResponse(config =>
                    {
                        config.WithCookie(negotiatedCookie);
                    }));
                }));
            });

            // When
            var response = browser.Get("/", with =>
            {
                with.Accept("test/test", 0.9m);
            });

            // Then
            Assert.Same(negotiatedCookie, response.Cookies.First());
        }
Beispiel #45
0
        private void UpdateTraceCookie(NancyContext ctx, Guid sessionGuid)
        {
            var cookie = new NancyCookie("__NCTRACE", sessionGuid.ToString(), true)
            {
                Expires = DateTime.Now.AddMinutes(30)
            };

            ctx.Response = ctx.Response.WithCookie(cookie);
        }
Beispiel #46
0
        public void Should_not_add_secure_if_set_to_false()
        {
            var cookie = new NancyCookie("Test", "Value");

            var result = cookie.ToString();

            result.ShouldNotContain("Secure");
        }
Beispiel #47
0
        public void Should_stringify_everyting()
        {
            // Given
            var date = new DateTime(2016, 11, 8, 9, 10, 11, DateTimeKind.Utc);
            var tuesday = GetInvariantAbbreviatedWeekdayName(date);
            var november = GetInvariantAbbreviatedMonthName(date);
            var cookie = new NancyCookie("paul", "blind") { Expires = date, Path = "/frank", Domain = "gmail.com" };

            // When
            var stringified = cookie.ToString();

            // Then
            stringified.ShouldEqual(string.Format("paul=blind; path=/frank; expires={0}, 08-{1}-2016 09:10:11 GMT; domain=gmail.com", tuesday, november));
        }
Beispiel #48
0
        /// <summary>
        /// Builds a cookie for logging a user out
        /// </summary>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildLogoutCookie(FormsAuthenticationConfiguration configuration)
        {
            var cookie = new NancyCookie(formsAuthenticationCookieName, String.Empty, true, configuration.RequiresSSL, DateTime.Now.AddDays(-1));

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return cookie;
        }
Beispiel #49
0
        /// <summary>
        /// Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration)
        {
            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);

            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL, cookieExpiry);

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return cookie;
        }
Beispiel #50
0
        /// <summary>
        /// Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, DateTime? cookieExpiry, FormsAuthenticationConfiguration configuration)
        {
            var cookieContents = EncryptAndSignCookie(userIdentifier.ToString(), configuration);

            var cookie = new NancyCookie(formsAuthenticationCookieName, cookieContents, true) { Expires = cookieExpiry };

            return cookie;
        }
        /// <summary>
        ///     Build the forms authentication cookie
        /// </summary>
        /// <param name="userIdentifier">Authenticated user identifier</param>
        /// <param name="cookieExpiry">Optional expiry date for the cookie (for 'Remember me')</param>
        /// <param name="configuration">Current configuration</param>
        /// <returns>Nancy cookie instance</returns>
        private static INancyCookie BuildCookie(Guid userIdentifier, FormsAuthenticationConfiguration configuration)
        {
            var expiryTime = DateTime.UtcNow.AddMinutes(configuration.SlidingSessionExpirationMinutes);

            var authSessionId = configuration.AuthSessionIdStore.Add(userIdentifier, expiryTime);

            var cookieContents = EncryptAndSignCookie(authSessionId.ToString(), configuration);

            var cookie = new NancyCookie(FormsAuthenticationCookieName, cookieContents, true, configuration.RequiresSSL)
                             {
                                 Expires = expiryTime
                             };

            if (!string.IsNullOrEmpty(configuration.Domain))
            {
                cookie.Domain = configuration.Domain;
            }

            if (!string.IsNullOrEmpty(configuration.Path))
            {
                cookie.Path = configuration.Path;
            }

            return cookie;
        }