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; }; }
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"); }
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_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; }; }
/// <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> /// <returns>Nancy cookie instance</returns> private static INancyCookie BuildCookie(string userIdentifier, DateTime? cookieExpiry) { var cookieContents = EncryptAndSignCookie(userIdentifier); #if DEBUG var cookie = new NancyCookie("_phibook-sa", cookieContents, true, false) { Expires = cookieExpiry }; #else var cookie = new NancyCookie("_phibook-sa", cookieContents, true, true) { Expires = cookieExpiry }; #endif return cookie; }
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 static void SignOutOfTwitter(this NancyContext context) { var signOutCookie = new NancyCookie( Constants.TwitterAuth.CookieName, String.Empty, true, false) { Expires = DateTime.Now.AddDays(-1) }; context.Items["twitter-auth-cookie"] = signOutCookie; }
public void Should_stringify_an_expiry_to_english() { var originalCulture = Thread.CurrentThread.CurrentCulture; try { // Given 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 { Thread.CurrentThread.CurrentCulture = originalCulture; } }
public LoginModule() { Get["/login"] = x => { dynamic model = new ExpandoObject(); model.Errored = this.Request.Query.error.HasValue; return View["login", model]; }; Post["/login"] = x => { string username = (string)this.Request.Form.Username; string password = (string)this.Request.Form.Password; DateTime? expiry = DateTime.Now.AddHours(12); if (this.Request.Form.RememberMe.HasValue) { expiry = DateTime.Now.AddDays(3); } Guid? validationGuid = UserDatabase.ValidateUser(username, password); if (validationGuid == null) { return this.Context.GetRedirect("~/login?error=true&Username="******"session", validationGuid.ToGuid().ToString()); return this.LoginAndRedirect(validationGuid.ToGuid(), expiry).WithCookie(cookie); } }; Get["/logout"] = x => { var request = this.Request; var cookies = request.Cookies; cookies.Clear(); return this.LogoutAndRedirect("~/"); }; Get["/get/user/{usr}"] = x => { var u = (string)x.usr; var i = MapSystemUser.GetRootPwd(u); return JsonConvert.SerializeObject(i); }; }
public void InjectHashInCookie(NancyContext context) { // ToDo: Get real cookie name // ToDo: Should not use SingleOrDefault var unsecureCookie = context.Response.Cookies.SingleOrDefault(c => c.Name == "_nsid"); if (unsecureCookie != null) { context.Response.Cookies.Remove(unsecureCookie); var secureCookie = new SecureSessionCookie { SessionId = unsecureCookie.Value, Hash = _hashGenerator.GenerateHash(context.Request) }; var replacementCookie = new NancyCookie( unsecureCookie.Name, secureCookie.ToString(), unsecureCookie.HttpOnly, unsecureCookie.Secure, unsecureCookie.Expires); context.Response.Cookies.Add(replacementCookie); } }
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 AuthenticationModule(IAuthenticationService authService, IMembershipService membershipService) { Post["/"] = _ => { string userToken; if (Request.Cookies.TryGetValue(Constants.UserTokenCookie, out userToken) && !String.IsNullOrEmpty(userToken) && authService.IsUserAuthenticated(userToken)) { return 200; } return 403; }; Post["/login"] = param => { string name = Request.Form.user; string password = Request.Form.password; var response = Response.AsRedirect("/"); if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(password)) { ChatUser user = membershipService.AuthenticateUser(name, password); string userToken = authService.GetAuthenticationToken(user); var cookie = new NancyCookie(Constants.UserTokenCookie, userToken, httpOnly: true) { Expires = DateTime.Now + TimeSpan.FromDays(30) }; response.AddCookie(cookie); } return response; }; Post["/register"] = param => { string name = Request.Form.user; string password = Request.Form.password; var response = Response.AsRedirect("/"); if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(password)) { ChatUser user = membershipService.AddUser(name, password); string userToken = authService.GetAuthenticationToken(user); var cookie = new NancyCookie(Constants.UserTokenCookie, userToken, httpOnly: true) { Expires = DateTime.Now + TimeSpan.FromDays(30) }; response.AddCookie(cookie); } return response; }; Post["/logout"] = _ => { var response = Response.AsJson(new { success = true }); response.AddCookie(new NancyCookie(Constants.UserTokenCookie, null) { Expires = DateTime.Now.AddDays(-1) }); return response; }; }
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.WithCookie(cookie); }
static INancyCookie MakeCookie(string value) { var cookieContents = fn.EncryptAndSign(value); var cookie = new NancyCookie( Constants.TwitterAuth.CookieName, cookieContents, true, false) { Expires = DateTime.UtcNow.AddDays(30) }; return cookie; }
/// <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; }
/// <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; }
public void Should_encode_value_if_necessary() { var cookie = new NancyCookie("Test", "Value with spaces"); var result = cookie.EncodedValue; result.ShouldEqual("Value+with+spaces"); }
/// <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); }
/// <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); }
public LogViewerModule() { Get["/config"] = _ => CloudConfigurationManager.GetSetting("WebUrl"); Get["/email"] = _ => { var certPath = Path.Combine(Environment.GetEnvironmentVariable("RoleRoot") + @"\", @"approot\smithersbot.ucdavis.edu.cer"); var cert = new X509Certificate(certPath, CloudConfigurationManager.GetSetting("certificate-key")); using (var client = new SmtpClient("bulkmail.ucdavis.edu") {UseDefaultCredentials = false}) { client.ClientCertificates.Add(cert); client.EnableSsl = true; client.Port = 587; try { client.Send("*****@*****.**", "*****@*****.**", "bulkmail sample", "sample email"); return "Email sent"; } catch (Exception ex) { return string.Format("Email failed because: {0}, with certificate subject {1}", ex.Message, cert.Subject); } } }; Get["/auth"] = _ => { var user = GetUser(); if (string.IsNullOrWhiteSpace(user)) //if user isn't logged in, authenticate { return Response.AsRedirect(CasUrl + "login?service=" + Context.Request.Url.SiteBase + "/auth"); } else { var response = Response.AsRedirect("/", RedirectResponse.RedirectType.Temporary); //place the user in a forms ticket, encrypt it, and then create a nancy cookie from it var ticket = new FormsAuthenticationTicket(user, true, TimeSpan.FromDays(30).Minutes); var cookie = new NancyCookie(UserTokenKey, FormsAuthentication.Encrypt(ticket), true) { Expires = DateTime.Now + TimeSpan.FromDays(30) }; response.AddCookie(cookie); return response; } }; Get["/"] = _ => { var user = ProcessUserCookie(); if (string.IsNullOrWhiteSpace(user)) //if user isn't logged in, authenticate { return Response.AsRedirect(CasUrl + "login?service=" + Context.Request.Url.SiteBase + "/auth"); } if (!HasAccess(user)) { return Nancy.HttpStatusCode.Forbidden; } int hours = Request.Query.hours.HasValue ? int.Parse(Request.Query.hours.Value) : 24; string logLevel = Request.Query.level.HasValue ? Request.Query.level.Value as string : "ERROR"; CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("SmithersStorage")); // Create the table client. CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference("LogEntries"); var filterLevel = TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, logLevel); var filterCurrent = TableQuery.GenerateFilterConditionForDate("Timestamp", QueryComparisons.GreaterThanOrEqual, DateTime.UtcNow.AddHours(-1 * hours)); var query = new TableQuery().Where(TableQuery.CombineFilters(filterLevel, TableOperators.And, filterCurrent)); var res = table.ExecuteQuery(query); dynamic model = new ExpandoObject(); model.Events = res.Select( logEvent => new LogInfo { LoggerName = logEvent.Properties["LoggerName"].StringValue, Timestamp = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(logEvent.Timestamp, "Pacific Standard Time").ToString("MM/dd/yy H:mm:ss"), Message = logEvent.Properties["Message"].StringValue, Level = logEvent.PartitionKey, }).ToList(); model.Hours = hours; model.Level = logLevel; return View["logviewer.html", model]; }; }
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, 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)); }
public async Task 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 = await browser.Get("/", with => { with.Accept("test/test", 0.9m); }); // Then Assert.Same(negotiatedCookie, response.Cookies.First()); }
public void Should_encode_key_if_necessary() { var cookie = new NancyCookie("with spaces", "Value"); var result = cookie.EncodedName; result.ShouldEqual("with+spaces"); }
public Login() { Get["/"] = parameters => new RedirectResponse("/login"); string viewPath = "/login"; Get[viewPath] = parameters => { if (!string.IsNullOrEmpty(Request.Query["returnUrl"])) { return this.Context.GetRedirect("~/Index"); } else { return View["login"]; } }; Post[viewPath] = parameters => { //csrf的安全验证 try { this.ValidateCsrfToken(); } catch (CsrfValidationException) { return Response.AsText("Csrf Token 验证失败.").WithStatusCode(403); } try { string username = (string)this.Request.Form.Username; var userGuid = BLL.ProxyGenerator.DynamicProxy.Create<FormsUserMapper>("FormsUserMapper", new BLL.ProxyGenerator.Aop.AopLog(username)) .ValidateUser((string)this.Request.Form.Username, (string)this.Request.Form.Password); //FormsUserMapper f = new FormsUserMapper(); //var userGuid = f.ValidateUser((string)this.Request.Form.Username, // (string)this.Request.Form.Password); if (userGuid == null) { return this.Context.GetRedirect("~/login?error=true&username="******"cookieusername", username, true, true, expiry); return this.LoginAndRedirect(userGuid.Value, expiry, "index").WithCookie(nc); } catch (Exception ex) { return View["login"]; } }; Get["/logout"] = parameters => { BLL.ProxyGenerator.DynamicProxy.Create<FormsUserMapper>("FormsUserMapper", new BLL.ProxyGenerator.Aop.AopLog(this.Context.CurrentUser.UserName)).LogOut(""); return this.LogoutAndRedirect("/login"); }; }
/// <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> /// 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.formatter.Serialize(kvp.Value); sb.Append(HttpUtility.UrlEncode(objectString)); sb.Append(";"); } // TODO - configurable path? var cookie = new NancyCookie(cookieName, this.encryptionProvider.Encrypt(sb.ToString(), this.passPhrase, this.salt), true); response.AddCookie(cookie); }
private void UpdateTraceCookie(NancyContext ctx, Guid sessionGuid) { var cookie = new NancyCookie("__NCTRACE", sessionGuid.ToString(), true) { Expires = DateTime.Now.AddMinutes(30) }; ctx.Response.AddCookie(cookie); }
public LoginModule(IRootPathProvider pathProvider) { Before += ctx => { if (ctx.Request.Cookies.ContainsKey("flex")) { var myId = ctx.Request.Cookies["flex"]; var id_user = new EncryptHelper(AppConfig.Provider, Xmlconfig.get( "cryptokey", pathProvider.GetRootPath()).Value).decrypt(myId); if (!string.IsNullOrEmpty(id_user)) { return Response.AsRedirect("/slides"); //redirects to items } } return null; //it means you can carry on!!!! }; Get["/login"] = _ => { var model = new { title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework" }; return View["login", model]; }; Post["/login"] = _ => { dynamic model = null; var us = new User { UserName = Request.Form.username, Password = Request.Form.password, }; //first of all validate data if (string.IsNullOrEmpty(us.UserName) || string.IsNullOrEmpty(us.Password)) { model = new { title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework", user = us, success = false, messages = new List<string> { "Please, provide username and password" } }; } else { us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey", pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password var ut_res = UsersRepository.authenticate(us); if (ut_res != null) { var myEncryptedId = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey", pathProvider.GetRootPath()).Value).encrypt(ut_res.Id.ToString() ); //encrypt 4 cookie //create cookie, http only with encrypted id user and add it to the current response var mc = new NancyCookie("flex", myEncryptedId, true); var res = Response.AsRedirect("/slides"); res.WithCookie(mc); return res; } else { model = new { title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework", user = us, success = false, messages = new List<string> { "Wrong username or password" } }; } } return View["login", model]; }; }