protected void Prijava_OnClick(object sender, ImageClickEventArgs e) { Korisnici korisnik = korisniciService.PrijaviKorisnikaPoKorisnickomImenuLozinci(tbKorisnickoIme.Text, tbLozinka.Text); if (korisnik != null) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, tbKorisnickoIme.Text, DateTime.Now, DateTime.Now.AddMinutes(120), chkZapamtiMe.Checked, "custom data"); string cookieStr = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieStr); if (chkZapamtiMe.Checked) cookie.Expires = ticket.Expiration; cookie.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(cookie); Response.Redirect("User/Default.aspx", true); } else { phStatusPrijave.Visible = true; lblStatusPrijave.Text = "Pogresni korisnicko ime ili lozinka!"; } }
private void cmdLogin_ServerClick(object sender, System.EventArgs e) { if (ValidateUser(txtUserName.Value, txtUserPass.Value)) { FormsAuthenticationTicket tkt; string cookiestr; HttpCookie ck; tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now, DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data"); cookiestr = FormsAuthentication.Encrypt(tkt); ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); if (chkPersistCookie.Checked) ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; Response.Cookies.Add(ck); string strRedirect; strRedirect = Request["ReturnUrl"]; if (strRedirect == null) strRedirect = "default.aspx"; Response.Redirect(strRedirect, false); } else { Response.Redirect("logon.aspx", false); } }
/// <summary> /// 生成一个Cookie,其中的token是 sha1(name + sha1(password) + ip + ua) /// </summary> void sendCookie(string name, string passwordHash) { string ua = HttpContext.Current.Request.UserAgent; if (ua == null) { ua = String.Empty; } // 如果用户通过代理服务器访问,获取到的将是代理服务器的ip。此ip不可随意伪造。 string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; if (ip == null) //我想一般不会有这种情况。 { ip = String.Empty; } //发送Cookie HttpCookie userInfo = new HttpCookie("admin"); userInfo.Values["name"] = name; userInfo.Values["token"] = getHash.getSHA1(name + passwordHash + ip + ua); if (Login1.RememberMeSet) { userInfo.Expires = DateTime.Now.AddDays(15); // 15天记住我 } Response.Cookies.Add(userInfo); }
protected void Page_Init(object sender, EventArgs e) { // The code below helps to protect against XSRF attacks var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { // Use the Anti-XSRF token from the cookie _antiXsrfTokenValue = requestCookie.Value; Page.ViewStateUserKey = _antiXsrfTokenValue; } else { // Generate a new Anti-XSRF token and save to the cookie _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); Page.ViewStateUserKey = _antiXsrfTokenValue; var responseCookie = new HttpCookie(AntiXsrfTokenKey) { HttpOnly = true, Value = _antiXsrfTokenValue }; if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) { responseCookie.Secure = true; } Response.Cookies.Set(responseCookie); } Page.PreLoad += master_Page_PreLoad; }
public IList<CartItem> GetCartFromCookies() { IList<CartItem> CartItems = new List<CartItem>(); HttpRequest Request = HttpContext.Current.Request; HttpResponse Response = HttpContext.Current.Response; HttpServerUtility Server = HttpContext.Current.Server; string cookieName = "_cart"; HttpCookie cookie = Request.Cookies[cookieName]; if (cookie == null) { cookie = new HttpCookie(cookieName, "[]"); Response.Cookies.Add(cookie); return CartItems; } string cartJson = Server.UrlDecode(cookie.Value); Newtonsoft.Json.Linq.JArray arrya = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JArray>(cartJson); if (CartItems == null) { cookie.Value = "[]"; Response.Cookies.Add(cookie); return CartItems; } CartItems = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<CartItem>>(cartJson); return CartItems; }
/// <summary> /// 判断是否保存用户名和密码 /// </summary> public void IsRemember() { if (chkRemember.Checked) { HttpCookie User_Account = new HttpCookie("User_Account", Server.UrlEncode(txtAccount.Text.Trim())); HttpCookie User_Password = new HttpCookie("User_Password", txtPassword.Text.Trim()); User_Account.Expires = DateTime.Now.AddMonths(1); User_Password.Expires = DateTime.Now.AddMonths(1); Response.Cookies.Add(User_Account); Response.Cookies.Add(User_Password); } else { HttpCookie User_Account = new HttpCookie("User_Account"); HttpCookie User_Password = new HttpCookie("User_Password"); User_Account.Expires = DateTime.Now.AddSeconds(-1); User_Password.Expires = DateTime.Now.AddSeconds(-1); Response.Cookies.Add(User_Account); Response.Cookies.Add(User_Password); } }
protected void Page_Init(object sender, EventArgs e) { // Код ниже защищает от XSRF-атак var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { // Использование маркера Anti-XSRF из cookie _antiXsrfTokenValue = requestCookie.Value; Page.ViewStateUserKey = _antiXsrfTokenValue; } else { // Создание нового маркера Anti-XSRF и его сохранение в cookie _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); Page.ViewStateUserKey = _antiXsrfTokenValue; var responseCookie = new HttpCookie(AntiXsrfTokenKey) { HttpOnly = true, Value = _antiXsrfTokenValue }; if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) { responseCookie.Secure = true; } Response.Cookies.Set(responseCookie); } Page.PreLoad += master_Page_PreLoad; }
protected void Button1_Click(object sender, EventArgs e) { FormsAuthentication.Initialize(); // Initializes the FormsAuthentication object based on the configuration settings for the application. SqlConnection con = new SqlConnection("server=saurabh-pc;database=ss;integrated security=true"); SqlCommand cmd = new SqlCommand("select role from roles r inner join users u on r.ID=u.roleid where u.username=@username and u.password=@password",con); cmd.Parameters.Add("@username", SqlDbType.VarChar, 30).Value = TextBox1.Text; cmd.Parameters.Add("@password", SqlDbType.VarChar, 30).Value = TextBox2.Text; FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox2.Text, "md5"); // Or "sha1" con.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { // Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version TextBox1.Text, // Username associated with ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire true, // "true" for a persistent user cookie dr.GetString(0), // User-data, in this case the roles FormsAuthentication.FormsCookiePath // Path cookie valid for ); // Encrypt the cookie using the machine key for secure transport string hash = FormsAuthentication.Encrypt(ticket); HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,// Name of auth cookie hash); // Hashed ticket // Set the cookie's expiration time to the tickets expiration time if (ticket.IsPersistent) { ck.Expires = ticket.Expiration; } // Add the cookie to the list for outgoing response Response.Cookies.Add(ck); // Redirect to requested URL, or homepage if no previous page // requested string returnUrl=Request.QueryString["ReturnUrl"]; if (returnUrl == null) { returnUrl = "home.aspx"; } // Don't call FormsAuthentication.RedirectFromLoginPage since it // could // replace the authentication ticket (cookie) we just added Response.Redirect(returnUrl); } else { Label1.Text = "incorrect username/password"; } }
protected void btnSubmit_Click(object sender, EventArgs e) { string name = this.txtUserName.Text.Trim(); string pwd = this.txtPassword.Text.Trim(); try { if (name.Length == 0 || pwd.Length == 0) { MessageBox.Show(this, "user name and password cannot be empty."); return; } if (user.Login(name, pwd)) { Session["User"] = name; UserDAL.LoginUserID = name; if (this.chkRem.Checked) { HttpCookie userid = new HttpCookie("UserName"); userid.Value = name; userid.Expires = DateTime.Now.AddDays(7); Response.Cookies.Add(userid); } else { Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1); } Response.Redirect("Default.aspx", true); } } catch (Exception ex) { MessageBox.Show(this, ex.Message); } }
/// <summary> /// 添加为Cookie.Values集合 /// </summary> /// <param name="cookieName"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expires"></param> public static void AddCookie(string cookieName, string key, string value, DateTime expires) { HttpCookie cookie = new HttpCookie(cookieName); cookie.Expires = expires; cookie.Values.Add(key, value); AddCookie(cookie); }
protected void Page_Load(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["BrowserDate"]; if (cookie == null) { cookie = new HttpCookie("BrowserDate"); cookie.Value = DateTime.Now.ToString(); cookie.Expires = DateTime.Now.AddDays(22); Response.Cookies.Add(cookie); } Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"))); if (Session["User"] == null) { Response.Redirect("~/Home.aspx"); } if (Request.QueryString["ID"] == null) Response.Redirect("Home.aspx"); if (dat.HasEventPassed(Request.QueryString["ID"].ToString())) { DataView dvName = dat.GetDataDV("SELECT * FROM Events WHERE ID="+ Request.QueryString["ID"].ToString()); Response.Redirect(dat.MakeNiceName(dvName[0]["Header"].ToString()) + "_" + Request.QueryString["ID"].ToString() + "_Event"); } }
protected void RegisterForCourses_Click(object sender, EventArgs e) { HttpCookie ConferencesCoursesRegistering = new HttpCookie("CoursesToRegisterFor"); ConferencesCoursesRegistering.Expires = DateTime.Now.AddMinutes(20); ConferencesCoursesRegistering.Path = "/"; Dictionary<string, Dictionary<string, float>> coursesToRegisterFor = new Dictionary<string, Dictionary<string, float>>(); List<Conference> chosenConferences = new List<Conference>(); int coursesChecked = 0; foreach (GridViewRow row in coursesForAllConferences.Rows) { Conference newConference = new Conference(row.Cells[0].Text); CheckBox registerForCourse = ((CheckBox)row.Cells[7].FindControl("RegisterForEventCB")); if (registerForCourse.Checked) { coursesChecked += 1; ConferencesCoursesRegistering.Values.Add(row.Cells[1].Text, row.Cells[0].Text); } } if (coursesChecked > 0) { Response.Cookies.Add(ConferencesCoursesRegistering); Response.Redirect("FinalizeRegistration.aspx"); } else { OneEventChosen.IsValid = false; } }
protected void AddAgendaItem(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["BrowserDate"]; if (cookie == null) { cookie = new HttpCookie("BrowserDate"); cookie.Value = DateTime.Now.ToString(); cookie.Expires = DateTime.Now.AddDays(22); Response.Cookies.Add(cookie); } Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"))); AgendaItemTextBox.Text = dat.stripHTML(AgendaItemTextBox.Text.Trim()); AgendaDescriptionTextBox.Text = dat.stripHTML(AgendaDescriptionTextBox.Text.Trim()); if (AgendaItemTextBox.Text.Trim() != "") { AgendaLiteral.Text += "<div style=\"padding: 0px; padding-bottom: 3px;\" class=\"AddLink\">" + dat.BreakUpString(AgendaItemTextBox.Text.Trim(), 44) + "</div>"; if (AgendaDescriptionTextBox.Text.Trim() != "") { AgendaLiteral.Text += "<div style=\"padding: 0px; padding-left: 20px; padding-bottom: 3px; color: #cccccc; font-family: arial; font-size: 11px;\">" + dat.BreakUpString(AgendaDescriptionTextBox.Text.Trim(), 44) + "</div>"; } } else { AgendaErrorLabel.Text = "Must include the item title."; } }
protected void DDLJezik_SelectedIndexChanged(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("Postavke"); cookie.Values["jezik"] = DDLJezik.SelectedValue; cookie.Expires.AddMonths(1); Response.Cookies.Add(cookie); }
protected void Page_Init(object sender, EventArgs e) { // El código siguiente ayuda a proteger frente a ataques XSRF var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { // Utilizar el token Anti-XSRF de la cookie _antiXsrfTokenValue = requestCookie.Value; Page.ViewStateUserKey = _antiXsrfTokenValue; } else { // Generar un nuevo token Anti-XSRF y guardarlo en la cookie _antiXsrfTokenValue = Guid.NewGuid().ToString("N"); Page.ViewStateUserKey = _antiXsrfTokenValue; var responseCookie = new HttpCookie(AntiXsrfTokenKey) { HttpOnly = true, Value = _antiXsrfTokenValue }; if (FormsAuthentication.RequireSSL && Request.IsSecureConnection) { responseCookie.Secure = true; } Response.Cookies.Set(responseCookie); } Page.PreLoad += master_Page_PreLoad; }
protected void OnActionGrid_PageSizeChanged(object source, GridPageSizeChangedEventArgs e) { HttpCookie actionGridPageSizeCookie = new HttpCookie("cand_actgrdps"); actionGridPageSizeCookie.Expires.AddDays(30); actionGridPageSizeCookie.Value = e.NewPageSize.ToString(); Response.Cookies.Add(actionGridPageSizeCookie); }
protected void btnCookie_Click(object sender, EventArgs e) { //luodaan keksi ja kirjoitetaan siihen viesti HttpCookie cookie = new HttpCookie("Message", txtMessage.Text); cookie.Expires = DateTime.Now.AddMinutes(15); Response.Cookies.Add(cookie); }
protected void Page_Load(object sender, EventArgs e) { string tmp = RndNum(5); HttpCookie a = new HttpCookie("ImageV", tmp); Response.Cookies.Add(a); this.ValidateCode(tmp); }
private void CreateCookie(string period) { if (Request.Cookies[cookieName] == null) { HttpCookie cookie = new HttpCookie("UserAccount"); cookie["username"] = txtUserName.Text; cookie["password"] = txtPassword.Text; //cookie["password"] = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text, "MD5"); //如果要对保存的密码加密,使用注释的语句 switch (period) { case "保存一天": cookie.Expires = DateTime.Now.AddDays(1); break; case "保存一月": cookie.Expires = DateTime.Now.AddMonths(1); break; case "保存一年": cookie.Expires = DateTime.Now.AddYears(1); break; default: break; } Response.Cookies.Add(cookie); } }
void promijeniBoju(string boja) { //Change color of background switch (boja) { case "Crvena": body.Attributes["style"] = "background-color:red;"; break; case "Roza": body.Attributes["style"] = "background-color:pink;"; break; case "Zelena": body.Attributes["style"] = "background-color:green;"; break; default: body.Attributes["style"] = "background-color:white;"; break; } //Save to cookie HttpCookie cookie = new HttpCookie("postavke"); cookie.Values["boja"] = boja; //save color name to cookie values cookie.Expires = DateTime.Now.AddMonths(2); // Keep cookie for two months // cookie.Expires = DateTime.Now.AddDays(-1); // get rid of cookie Response.Cookies.Add(cookie); //include in postback }
private void Member_logOut() { HttpContext.Current.Session.Abandon(); //Session.Clear(); HttpCookie c = new HttpCookie("securityToken"); c.Expires = DateTime.Now.AddHours(-1); SiteCookie.RemoveAll(); FormsAuthentication.SignOut(); HttpCookie oldCookie = new HttpCookie(".ASPXAUTH"); oldCookie.Expires = DateTime.Now.AddDays(-1); HttpContext.Current.Response.Cookies.Add(oldCookie); //// clear authentication cookie HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); cookie1.Expires = DateTime.Now.AddDays(-1); HttpContext.Current.Response.Cookies.Add(cookie1); // clear session cookie (not necessary for your current problem but i would recommend you do it anyway) HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", ""); cookie2.Expires = DateTime.Now.AddDays(-1); HttpContext.Current.Response.Cookies.Add(cookie2); cookie2 = new HttpCookie("ClientRememberUserCookieTime", DateTime.MinValue.ToString()); cookie2.Expires = DateTime.Now.AddDays(-1); HttpContext.Current.Response.Cookies.Add(cookie2); HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); HttpContext.Current.Response.Cache.SetNoStore(); Response.Redirect("/", false); }
protected void RemoveMember(object sender, EventArgs e) { HttpCookie cookie = Request.Cookies["BrowserDate"]; if (cookie == null) { cookie = new HttpCookie("BrowserDate"); cookie.Value = DateTime.Now.ToString(); cookie.Expires = DateTime.Now.AddDays(22); Response.Cookies.Add(cookie); } Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"))); dat.Execute("DELETE FROM User_Friends WHERE UserID=" + Session["User"].ToString() + " AND FriendID =" + Request.QueryString["ID"].ToString()); dat.Execute("DELETE FROM User_Friends WHERE UserID=" + Request.QueryString["ID"].ToString() + " AND FriendID =" + Session["User"].ToString()); dat.Execute("DELETE FROM UserFriendPrefs WHERE UserID=" + Session["User"].ToString() + " AND FriendID =" + Request.QueryString["ID"].ToString()); dat.Execute("DELETE FROM UserFriendPrefs WHERE UserID=" + Request.QueryString["ID"].ToString() + " AND FriendID =" + Session["User"].ToString()); RemovePanel.Visible = false; ThankYouPanel.Visible = true; }
/// <summary> /// Click event for authorize button. Validates the user's credentials against the locked trip /// and sets cookies for session authentication. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btn_auth_Click(object sender, EventArgs e) { Trip trip = GetTrip(Request["id"]); if (trip == null) { return; } string password = TripAuthPassword.Text; //Clear input box TripAuthPassword.Text = ""; if (String.IsNullOrWhiteSpace(password)) { return; } string hash = Trip.GetSHA1Hash(password); if (hash == trip.Password) { string token = Trip.GetMD5Hash(Session.SessionID); HttpCookie cookie = new HttpCookie("authtoken", token); Response.Cookies.Add(cookie); Session[token] = trip.ID; //Response.Cookies["authsession"][hash] = trip.ID; //Response.Cookies["authsession"].Expires = DateTime.Now.AddHours(1); //Redirect to prevent accidental resubmission Response.Redirect(Request.Url.ToString(), false); } }
/* * Setup session variables & check for authentication */ protected void Page_Load(object sender, EventArgs evt) { if (!Page.IsPostBack) { string server = Request.QueryString["server"]; if (server != null) { server = HttpUtility.UrlDecode(server); Session["FieldScope_MetaLens_Server"] = server; } else { server = (string)Session["FieldScope_MetaLens_Server"]; } string lat = Request.QueryString["lat"]; if (lat != null) { lat = HttpUtility.UrlDecode(lat); Session["FieldScope_MetaLens_Latitude"] = lat; } else { lat = (string)Session["FieldScope_MetaLens_Latitude"]; } string lon = Request.QueryString["lon"]; if (lon != null) { lon = HttpUtility.UrlDecode(lon); Session["FieldScope_MetaLens_Longitude"] = lon; } else { lon = (string)Session["FieldScope_MetaLens_Longitude"]; } if ((!Request.Cookies.AllKeys.Contains("MetaLens_Cookie")) || (MetaLens.Service.CheckLogin(server, Request.Cookies["MetaLens_Cookie"].Value) == null)) { HttpCookie cookie = new HttpCookie("MetaLens_Cookie", MetaLens.Service.Login(server, USERNAME, PASSWORD)); cookie.Expires = DateTime.Now.AddMinutes(60); Response.SetCookie(cookie); } } }
protected void Page_Load(object sender, EventArgs e) { HtmlMeta hm = new HtmlMeta(); HtmlHead head = (HtmlHead)Page.Header; hm.Name = "ROBOTS"; hm.Content = "NOINDEX, FOLLOW"; head.Controls.AddAt(0, hm); HttpCookie cookie = Request.Cookies["BrowserDate"]; if (cookie == null) { cookie = new HttpCookie("BrowserDate"); cookie.Value = DateTime.Now.ToString(); cookie.Expires = DateTime.Now.AddDays(22); Response.Cookies.Add(cookie); } Data dat = new Data(DateTime.Parse(cookie.Value.ToString().Replace("%20", " ").Replace("%3A", ":"))); DataView dvGroup = dat.GetDataDV("SELECT * FROM Groups WHERE ID="+Request.QueryString["ID"].ToString()); if (dvGroup[0]["Host"].ToString() == Session["User"].ToString()) { TheLabel.Text = "Since you are the primary host of the group, you must first designate another host for the group. Go to your group's home page and click on 'Edit Members' Prefs'."; Button3.Visible = false; } }
protected void btnLogin_Click(object sender, EventArgs e) { bool IsAuthenticated = false; try { IsAuthenticated = Account.AuthenticateUser(txtUserName.Text, txtEmail.Text, txtPassword.Text); if (IsAuthenticated) { //set cookie with login time HttpCookie loginCookie = new HttpCookie("loginCookie"); loginCookie.Value = DateTime.Now.ToString(); Response.Cookies.Add(loginCookie); Response.Redirect("Default.aspx"); } else { lblError.Text = "Sorry, your credentials were not recognized. Access denied! :( "; lblError.Visible = true; } } catch (Exception ex) { lblError.Text = ex.Message.ToString(); lblError.Visible = true; } }
protected void logueo_Click(object sender, EventArgs e) { HttpCookie page = new HttpCookie("carrito"); page.Values["value"] = "Carrito.aspx"; Response.Cookies.Add(page); Response.Redirect("Login.aspx"); }
protected void Page_Load(object sender, EventArgs e) { switch (Request.QueryString["Mode"]) { case "Location": { HttpCookie _locationCookies = new HttpCookie("Location"); _locationCookies["LocationId"] = Request.QueryString["LocationId"]; _locationCookies["LocationName"] = Request.QueryString["LocationName"]; _locationCookies.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(_locationCookies); break; } case "Language": { HttpCookie _LanguageCookies = new HttpCookie("Language"); _LanguageCookies["LanguageId"] = Request.QueryString["LanguageId"]; _LanguageCookies["LanguageName"] = Request.QueryString["LanguageName"]; _LanguageCookies.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(_LanguageCookies); break; } } Response.Redirect(Request.UrlReferrer.ToString()); }
protected void validateUserEmail(object sender, LoginCancelEventArgs e) { TextBox EmailAddressTB = ((TextBox)PWRecovery.UserNameTemplateContainer.FindControl("EmailAddressTB")); Literal ErrorLiteral = ((Literal)PWRecovery.UserNameTemplateContainer.FindControl("ErrorLiteral")); MembershipUser mu = Membership.GetUser(PWRecovery.UserName); if (mu != null) // The username exists { if (mu.Email.Equals(EmailAddressTB.Text)) // Their email matches { //ProfileCommon newProfile = Profile.GetProfile(PWRecovery.UserName); HttpCookie appCookie = new HttpCookie("usernameCookie"); //appCookie.Value = newProfile.FullName; appCookie.Expires = DateTime.Now.AddMinutes(3); Response.Cookies.Add(appCookie); ErrorLiteral.Text = "An email has been sent to your email account with a new password."; } else { e.Cancel = true; ErrorLiteral.Text = "Your username and password do not match"; } } else { e.Cancel = true; ErrorLiteral.Text = "No such user found."; } }
public static void Destroy(string cookieIdentifier) { HttpCookie myCookie = new HttpCookie(cookieIdentifier); HttpContext.Current.Response.Cookies.Remove(cookieIdentifier); HttpContext.Current.Response.Cookies.Add(myCookie); HttpContext.Current.Response.Cookies[cookieIdentifier].Expires = DateTime.Now.AddDays(-15); }
public ActionResult Login(String nombre, String passw) { String rol = ""; if (nombre == "usuario" && passw == "usuario") { rol = nombre; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, nombre, DateTime.Now, DateTime.Now.AddMinutes(5), true, rol); String cifrado = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie("TicketUsuario", cifrado); Response.Cookies.Add(cookie); ViewBag.Login = "******"; return(RedirectToAction("UsuariosLogueados", "Home")); } else if (nombre == "admin" && passw == "admin") { rol = nombre; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket (1, nombre, DateTime.Now, DateTime.Now.AddMinutes(5), true, rol); String cifrado = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie("TicketUsuario", cifrado); Response.Cookies.Add(cookie); ViewBag.Login = "******"; return(RedirectToAction("Trabajadores", "Home")); } else { ViewBag.Login = "******"; return(View()); } }
// ************************************** // URL: /Account/AutoLogIn // ************************************** // TODO: inactivate this action when publish public ActionResult AutoLogInOnlyEditor(string returnUrl) { IUserContext userContext = CoreData.UserManager.Login("Testuseronlyeditor", "TestUser11", Resources.DyntaxaSettings.Default.DyntaxaApplicationIdentifier); if (userContext.IsNotNull()) { Session["userContext"] = userContext; userContext.Locale = CoreData.LocaleManager.GetLocale(userContext, LocaleId.en_GB); // Must clear the service cash so that roles can be reloded. // CoreData.TaxonManager.ClearCacheForUserRoles(userContext); /* globalization with cookie */ HttpCookie cookie = new HttpCookie("CultureInfo"); cookie.Value = userContext.Locale.ISOCode; cookie.Expires = DateTime.Now.AddYears(1); Response.Cookies.Add(cookie); Thread.CurrentThread.CurrentUICulture = userContext.Locale.CultureInfo; Thread.CurrentThread.CurrentCulture = userContext.Locale.CultureInfo; FormsService.SignIn("Testuseronlyeditor"); this.RedrawTree(); } else { ModelState.AddModelError("", Resources.DyntaxaResource.AccountControllerIncorrectLoginError); } if (string.IsNullOrEmpty(returnUrl)) { return RedirectToAction("SearchResult", "Taxon"); } return Redirect(returnUrl); }
void Application_PostAuthenticateRequest(object sender, EventArgs e) { System.Web.HttpContext.Current.SetSessionStateBehavior( SessionStateBehavior.Required); HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { ClientUserData clientUserData = null; try { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); clientUserData = JsonConvert.DeserializeObject <ClientUserData>(authTicket.UserData); } catch { } if (HttpContext.Current != null && clientUserData != null) { HttpContext.Current.User = new ICustomPrincipal(clientUserData); } } }
public static void DeleteCookie() { if (CacheRolesInCookie) { HttpContext context = HttpContext.Current; if (context == null) { throw new HttpException("Context is null."); } HttpResponse response = context.Response; if (response == null) { throw new HttpException("Response is null."); } HttpCookieCollection cc = response.Cookies; cc.Remove(CookieName); HttpCookie expiration_cookie = new HttpCookie(CookieName, ""); expiration_cookie.Expires = new DateTime(1999, 10, 12); expiration_cookie.Path = CookiePath; cc.Add(expiration_cookie); } }
public override string GetVaryByCustomString(HttpContext context, string arg) { // It seems this executes multiple times and early, so we need to extract language again from cookie. if (arg == "culture") // culture name (e.g. "en-US") is what should vary caching { string cultureName = null; // Attempt to read the culture cookie from Request HttpCookie cultureCookie = Request.Cookies["_culture"]; if (cultureCookie != null) { cultureName = cultureCookie.Value; } else { cultureName = Request.UserLanguages[0]; // obtain it from HTTP header AcceptLanguages } // Validate culture name cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe return(cultureName.ToLower()); // use culture name as cache key, "es", "en-us", "es-cl", etc. } return(base.GetVaryByCustomString(context, arg)); }
protected void btnCheckIR_Click(object sender, EventArgs e) { HttpCookie ck = Request.Cookies["MaGDV"]; if (ck == null) { Response.Write("<script> alert('Please login again!');</script>"); } else { string id = mClaimID; DataTable dt = new DataTable(); int idgdv = int.Parse(Request.Cookies["MaGDV"].Value); bool up = claimDao.UpdateCheckIR(id, idgdv); if (up == true) { loadSIGNCheck(id); } else { Response.Write("<script> alert('Update preparer error!');</script>"); } } }
public IHttpResponse Login(LoginUserViewModel model) { var hashedPassword = this.hashService.Hash(model.Password); var user = this.DbContext.Users.SingleOrDefault(u => u.Username == model.Username && u.Password == hashedPassword); if (user == null) { return(this.BadRequestErrorWithView("Invalid username or password.")); } var mvcUser = new MvcUserInfo { Username = user.Username, Role = user.Role.ToString(), Info = user.Email, }; var cookieContent = this.UserCookieService.GetUserCookie(mvcUser); var cookie = new HttpCookie(".auth", cookieContent, 7); this.Response.Cookies.Add(cookie); return(this.Redirect("/")); }
public ActionResult UpdateCNInfo(int id, CNInfo cNInfo) { if (!ModelState.IsValid) { return(Json("Model is not valid", JsonRequestBehavior.AllowGet)); } if (id != cNInfo.CNInfoId) { return(Json("Model is not valid", JsonRequestBehavior.AllowGet)); } HttpCookie myCookie = Request.Cookies["UserCookie"]; cNInfo.AddBy = myCookie.Values["UserInfoId"].ToString(); db.Entry(cNInfo).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CNInfoExists(id)) { return(Json("Model not found", JsonRequestBehavior.AllowGet)); } else { throw; } } return(Json(cNInfo, JsonRequestBehavior.AllowGet)); }
private async Task SignInAsync(IdentityUser user, bool isPersistent) { try { Logger.Current.Informational("Logging out..user id: " + user.Id); AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); HttpCookie CartCookie = new HttpCookie("IsPersistent", isPersistent.ToString()); CartCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(CartCookie); string accountLogoUrl = "false"; ClaimsIdentity claimsIdentity = await user.GenerateUserIdentityAsync(UserManager); GetAccountImageStorageNameResponse response = accountService.GetStorageName(new GetAccountImageStorageNameRequest() { AccountId = user.AccountID }); if (response != null) { accountLogoUrl = response.AccountLogoInfo.StorageName != null?urlService.GetUrl(user.AccountID, ImageCategory.AccountLogo, response.AccountLogoInfo.StorageName) : accountLogoUrl; claimsIdentity.AddClaim(new Claim("AccountLogoUrl", accountLogoUrl)); claimsIdentity.AddClaim(new Claim("AccountName", response.AccountLogoInfo.AccountName)); HttpCookie helpURL = new HttpCookie("helpURL", response.AccountLogoInfo.HelpURL); helpURL.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(helpURL); } AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, claimsIdentity); } catch (Exception ex) { ExceptionHandler.Current.HandleException(ex, DefaultExceptionPolicies.LOG_ONLY_POLICY); } }
public ActionResult Login(Kullanici kl) { string ka = ValidateUser(kl.KullaniciAdi, kl.Parola); if (!string.IsNullOrEmpty(ka)) { //FormsAuthenticationTicket :Role göre kullanıcıya giriş yaptırmamızı sağlar FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "usercookie", DateTime.Now, DateTime.Now.AddMinutes(15), true, ka, FormsAuthentication.FormsCookiePath); //cookie leri tutacaz HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName); if (ticket.IsPersistent) { ck.Expires = ticket.Expiration; //cookie nin ölme süresi ticketin expirationuna bağlı olsun. } Response.Cookies.Add(ck); FormsAuthentication.RedirectFromLoginPage(kl.KullaniciAdi, true); } return(RedirectToAction("Index", "Home")); }
public string Login(string uname, string psw) { //get code from queryString //var initdata = initMemberData(); var temp = item.Members.Any(x => x.MemberEmail == uname); if (temp) { var membership = (from m in item.Members where m.MemberEmail == uname select m).ToList(); var password = Encryption.EncryptionMethod(psw, membership [0].MemberName); if (membership [0].MemberEmail == uname && password == membership [0].MemberPassword) { LoginProcess("Client", membership [0].MemberName, true, membership [0]); if (CheckAdmin(psw, password, "Admin")) { TempData["roles"] = "Admin"; HttpCookie rqsCookie = HttpContext.Request.Cookies.Get("myaccount"); var memberDataobj = FormsAuthentication.Decrypt(rqsCookie.Value); var memberData = JsonConvert.DeserializeObject <Member>(memberDataobj.UserData); TempData["username"] = memberData.MemberName; } else { TempData["roles"] = "Client"; HttpCookie rqsCookie = HttpContext.Request.Cookies.Get("myaccount"); var memberDataobj = FormsAuthentication.Decrypt(rqsCookie.Value); var memberData = JsonConvert.DeserializeObject <Member>(memberDataobj.UserData); TempData["username"] = memberData.MemberName; } return("1"); } return("3"); } return("2"); }
/// <summary> /// Determine the language needed from the HttpContext and set the language for the thread /// </summary> public static void SetLanguageFromContext() { string NewUICulture = ""; string NewCulture = ""; string languageParam = GetLanguageFromContext(); switch (languageParam.ToUpper()) { case "EN": NewUICulture = "en"; NewCulture = "en-US"; break; case "ES": NewUICulture = "es"; NewCulture = "es-ES"; break; } Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(NewCulture); Thread.CurrentThread.CurrentUICulture = new CultureInfo(NewUICulture); log.Debug("SetLanguageFromContext ( NewCulture = " + NewCulture + ")"); if (HttpContext.Current.Request.Cookies[cookieName] == null) { log.Debug("Creating cookie"); // Creamos elemento HttpCookie con su nombre y su valor HttpCookie myCookie = new HttpCookie(cookieName, NewUICulture); myCookie.Expires = DateTime.Now.AddDays(360); // Y finalmente añadimos la cookie a nuestro usuario HttpContext.Current.Response.Cookies.Add(myCookie); } }
public static void SetToken(Controller controller, string token) { if (AuthSaveType.Equals(AuthSaveType_Cookie, StringComparison.OrdinalIgnoreCase)) { if (controller.Response.Cookies[LoginCheckAttribute.AuthSaveKey] == null) { HttpCookie httpCookie = new HttpCookie(LoginCheckAttribute.AuthSaveKey, token); controller.Response.Cookies.Add(httpCookie); LogHelper.WriteInfo("token添加成功cookie1!"); } else { controller.Response.Cookies[LoginCheckAttribute.AuthSaveKey].Value = token; LogHelper.WriteInfo("token添加成功cookie2!"); } } else { controller.Session[LoginCheckAttribute.AuthSaveKey] = token; LogHelper.WriteInfo("token添加成功session!"); } LogHelper.WriteInfo("token添加完成!"); }
public ActionResult Register() { //Request - извлекать cookie-наборы //Response - устанавливать cookie-наборы HttpCookie cookie = new HttpCookie("MyCookie", "I will save the world !!!"); cookie.Expires = DateTime.Now.AddMinutes(5); Response.Cookies.Add(cookie); string browser = HttpContext.Request.Browser.Browser; string user_agent = HttpContext.Request.UserAgent; string url = HttpContext.Request.RawUrl; string ip = HttpContext.Request.UserHostAddress; string referrer = HttpContext.Request.UrlReferrer == null ? "" : HttpContext.Request.UrlReferrer.AbsoluteUri; // bool IsAdmin = HttpContext.User.IsInRole("admin"); // определяем, принадлежит ли пользователь к администраторам bool IsAuth = HttpContext.User.Identity.IsAuthenticated; // аутентифицирован ли пользователь string login = HttpContext.User.Identity.Name; // логин авторизованного пользователя return(View()); }
public override void SetCookie(HttpCookie cookie) { var ck = new CookieHeaderValue(cookie.Name, cookie.Value ?? "") { Domain = cookie.Domain, HttpOnly = cookie.HttpOnly, Path = cookie.Path, Secure = cookie.Secure && Url.Scheme == Uri.UriSchemeHttps, }; if (cookie.Value == null) { ck.MaxAge = TimeSpan.Zero; ck.Expires = DateTimeOffset.MinValue; Properties["#Cookie-" + Properties.Count] = ck; return; } if (cookie.Expires > DateTime.Now) { ck.Expires = cookie.Expires; } Properties["#Cookie-" + cookie.Name] = ck; }
private static void RequestParmToCookie(HttpContext context, WebSession webSession, string parmName, string slotName) { if (context.Request[parmName] == null) { return; } var parmValue = context.Request[parmName]; if (context.Request.Cookies[parmName] == null || !context.Request.Cookies[parmName].ToString().Equals(parmValue, StringComparison.InvariantCultureIgnoreCase)) { var cookie = new HttpCookie(parmName, parmValue) { HttpOnly = true }; context.Response.Cookies.Set(cookie); } if (webSession != null) { webSession.Set(slotName, parmValue); } }
/// <summary> /// /// </summary> /// <param name="cookieName"></param> public static void ExpireCookie(string cookieName) { HttpContext http = HttpContext.Current; //remove from the request http.Request.Cookies.Remove(cookieName); //expire from the response HttpCookie angularCookie = http.Response.Cookies[cookieName]; if (angularCookie != null) { //this will expire immediately and be removed from the browser angularCookie.Expires = DateTime.Now.AddYears(-1); } else { //ensure there's def an expired cookie http.Response.Cookies.Add(new HttpCookie(cookieName) { Expires = DateTime.Now.AddYears(-1) }); } }
public ICookie setupICookie() { //Mock IHttpContextAccessor var mockHttpContextAccessor = new Mock <IHttpContextAccessor>(); Mock <IDataProtector> mockDataProtector = new Mock <IDataProtector>(); Mock <IDataProtectionProvider> mockDataProtectionProvider = new Mock <IDataProtectionProvider>(); var cookieOption = new Mock <IOptions <CookieManagerOptions> >(); var context = new DefaultHttpContext(); //setup httpcontext mockHttpContextAccessor.Setup(_ => _.HttpContext).Returns(context); //setting up cookie collection mockHttpContextAccessor.Setup(_ => _.HttpContext.Request.Cookies).Returns(new RequestCookieCollection(cookieRequestHeaderList)); mockHttpContextAccessor.Setup(_ => _.HttpContext.Response.Cookies).Returns(new ResponseCookies(new HeaderDictionary(cookieResponseHeaders), null)); //setting up set-cookie headers mockHttpContextAccessor.Setup(_ => _.HttpContext.Response.Headers).Returns(new HeaderDictionary(cookieResponseHeaders)); httpContext = mockHttpContextAccessor.Object.HttpContext; //setting up dataprotector mockDataProtector.Setup(sut => sut.Protect(It.IsAny <byte[]>())).Returns(Encoding.UTF8.GetBytes("CfDJ8GnPj9ak8t1HphXa8mMbIoKnqw4YPtXOXoKasvmnPEhKDWkKreGRYzObYb6nsYj6zcIIiyuqWMic_lfwLkYv-Y-II7heGvYx0ffMSSIVD7JKrsX9ML74Ju2vmFPnhTtifbnFQBrUbluhJ2Pn34v3anAXHdYR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RC3nJwTfjj9XG855HTgcAtUJv9A9CKCHu2lkKoCRefyrCixa36Ch9YJ113Fwjmtz9p1sQseflENtYOhj1_FPZVUl7U-yNWAI30fazh40TDGj9qca3KlLiPfAosGTuouzU0h-PmihTfJImDlCbC6BobgA")); mockDataProtector.Setup(sut => sut.Unprotect(It.IsAny <byte[]>())).Returns(Encoding.UTF8.GetBytes(expectedTestString)); mockDataProtectionProvider.Setup(s => s.CreateProtector(It.IsAny <string>())).Returns(mockDataProtector.Object); //setting up cookie options cookieOption.Setup(s => s.Value).Returns(new CookieManagerOptions()); ICookie cookie = new HttpCookie(mockHttpContextAccessor.Object, mockDataProtectionProvider.Object, cookieOption.Object); return(cookie); }
public void SetCulture(String culture) { // Validate input culture = CultureHelper.GetImplementedCulture(culture); RouteData.Values["cultrue"] = culture; // Save culture in a cookie HttpCookie cookie = Request.Cookies["_culture"]; if (cookie != null) { cookie.Value = culture; } else { cookie = new HttpCookie("_culture"); cookie.Value = culture; cookie.Expires = DateTime.Now.AddYears(1); } Response.Cookies.Add(cookie); HttpContext.Response.Redirect(HttpContext.Request.UrlReferrer.AbsolutePath); }
protected void Page_Load(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("EmployeeName"); HttpCookie cookie1 = new HttpCookie("EmployeeId"); HttpCookie cookie2 = new HttpCookie("EmployeeDesignation"); HttpCookie cookie3 = new HttpCookie("EmployeeEmail"); HttpCookie cookie4 = new HttpCookie("EmployeeNumber"); //Assign value to the created cookie cookie.Value = " muntaj"; cookie1.Value = " 101"; cookie2.Value = " HR"; cookie3.Value = " [email protected]"; cookie4.Value = " 1234567890"; //add cookie to the response instance Response.Cookies.Add(cookie); Response.Cookies.Add(cookie1); Response.Cookies.Add(cookie2); Response.Cookies.Add(cookie3); Response.Cookies.Add(cookie4); //_____________________________Fetch the Cookie Created______________________// var Cookie_Value = Response.Cookies["EmployeeName"].Value; var Cookie1_Value = Response.Cookies["EmployeeId"].Value; var Cookie2_Value = Response.Cookies["EmployeeDesignation"].Value; var Cookie3_Value = Response.Cookies["EmployeeEmail"].Value; var Cookie4_Value = Response.Cookies["EmployeeNumber"].Value; l1.Text = Cookie_Value + "<br/>"; Label1.Text = Cookie1_Value + "<br/>"; Label2.Text = Cookie2_Value + "<br/>"; Label3.Text = Cookie3_Value + "<br/>"; Label4.Text = Cookie4_Value + "<br/>"; }
public ActionResult SubmitLogin(UserAccount obj) { if (ModelState.IsValid) { ReportsBLL Bll = new ReportsBLL(); var isValid = Bll.IsValidUser(obj.UserID, obj.Password); if (isValid) { Session["UserId"] = obj.UserID; FormsAuthentication.SetAuthCookie(obj.UserID, obj.RememberMe); //use RememberMe checkbox to decide if saving UserID or not if (obj.RememberMe) { HttpCookie cookie = new HttpCookie("Login"); cookie.Values.Add("UserID", obj.UserID); cookie.Expires = DateTime.Now.AddDays(15); Response.Cookies.Add(cookie); } else { HttpCookie cookie = new HttpCookie("Login"); cookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(cookie); } return(RedirectToAction("Product", "Product")); } ViewData["ErrorMessage"] = "UserID or Password is incorrect"; return(View("Login")); } else { return(View("Login")); } }
/// <summary> /// 添加一个Cookie,默认浏览器关闭过期 /// </summary> public static void SetCookie(string cookiename, System.Collections.Specialized.NameValueCollection cookievalue, int?days) { var cookie = HttpContext.Current.Request.Cookies[cookiename]; if (cookie == null) { cookie = new HttpCookie(cookiename); } ClearCookie(cookiename); cookie.Values.Add(cookievalue); var siteurl = System.Configuration.ConfigurationManager.AppSettings["siteurl"]; if (!string.IsNullOrEmpty(siteurl)) { cookie.Domain = siteurl.Replace("www.", ""); } if (days != null && days > 0) { cookie.Expires = DateTime.Now.AddDays(Convert.ToInt32(days)); } HttpContext.Current.Response.AppendCookie(cookie); }
/// <summary> /// Adds a product to a "compare products" list /// </summary> /// <param name="productId">Product identifier</param> public virtual void AddProductToCompareList(int productId) { var oldProductIds = GetComparedProductIds(); var newProductIds = new List <int>(); newProductIds.Add(productId); foreach (int oldProductId in oldProductIds) { if (oldProductId != productId) { newProductIds.Add(oldProductId); } } var compareCookie = _httpContext.Request.Cookies.Get(COMPARE_PRODUCTS_COOKIE_NAME); if (compareCookie == null) { compareCookie = new HttpCookie(COMPARE_PRODUCTS_COOKIE_NAME); compareCookie.HttpOnly = true; } compareCookie.Values.Clear(); int i = 1; foreach (int newProductId in newProductIds) { compareCookie.Values.Add("CompareProductIds", newProductId.ToString()); if (i == _catalogSettings.CompareProductsNumber) { break; } i++; } compareCookie.Expires = DateTime.Now.AddDays(10.0); _httpContext.Response.Cookies.Set(compareCookie); }
// GET: User public ActionResult Index() { HttpCookie cookie = Request.Cookies.Get("ChoTotUser"); if (Session["__USER__"] != null && !Session["__USER__"].Equals("")) { ViewBag.gUserStr = Session["__USER__"].ToString().Replace("\r\n", ""); ViewBag.isLoggingIn = false; } else if (cookie != null) { ViewBag.gUserStr = cookie["__USER__"].ToString().Replace("\r\n", ""); Session["__USER__"] = cookie["__USER__"]; ViewBag.isLoggingIn = false; } //Get all cities ds = Utils.getAllParameters(); List <City> lstCity = ds.Tables[0].AsEnumerable().Select( dataRow => new City { cityId = dataRow.Field <int>("cityId"), shortName = dataRow.Field <string>("shortName"), fullName = dataRow.Field <string>("fullName") }).ToList(); if (lstCity.Count > 0) { lstCity.RemoveAt(0); } ViewBag.selectListCity = new SelectList(lstCity, "cityId", "fullName"); ViewBag.ratingMin = ds.Tables[2].Rows[0]["ratingMin"]; ViewBag.ratingMax = ds.Tables[2].Rows[0]["ratingMax"]; ViewBag.ratingStep = ds.Tables[2].Rows[0]["ratingStep"]; return(View()); }
/// <summary> /// 根据HttpContext对象设置用户标识对象 /// </summary> /// <param name="context"></param> public static void SetUserInfo(HttpContext context) { if (context == null) { throw new ArgumentNullException("context"); } // 1. 读登录Cookie HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null || string.IsNullOrEmpty(cookie.Value)) { return; } try { Staffs userData = null; // 2. 解密Cookie值,获取FormsAuthenticationTicket对象 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false) { userData = JsonConvert.DeserializeObject <Staffs>(ticket.UserData); } if (ticket != null && userData != null) { context.User = new FormsPrincipal(ticket, userData); } } catch (Exception ex) { LogHelper.Error(typeof(FormsPrincipal), ex.Message, ex); } }
protected void Application_AuthorizeRequest(object sender, EventArgs e) { HttpCookie cookie = HttpContext.Current.Request.Cookies["Language"]; string userLang = ""; string rsLang = "en"; try { if (cookie == null) { cookie = new HttpCookie("Language"); } cookie.Value = rsLang; Response.Cookies.Add(cookie); //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(rsLang); //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(rsLang); } catch (Exception) { //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en"); //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en"); } }
/// <summary> /// Get user id from session or asp.net->db->session(keep); /// </summary> /// <returns>Return -1 when not found.</returns> public int GetUserID() { var useridCookie = HttpContext.Current.Request.Cookies[CookiesNames.UserID]; if (useridCookie != null) { int userid; if (int.TryParse(useridCookie.Value, out userid)) { return(userid); } } User user = GetUserSession(); if (user != null) { var cookieUser = new HttpCookie(Cookie.CookiesNames.UserID); cookieUser.Value = user.UserID.ToString(); cookieUser.Expires = DateTime.Now.AddDays(60); HttpContext.Current.Response.Cookies.Set(cookieUser); return(user.UserID); } return(-1); }
protected void Page_Load(object sender, EventArgs e) { if (Session["UserId"] == null) { Response.Redirect("~/Login.aspx"); } if (!IsPostBack) { bindLocation(); bindMAandProviders(); HttpCookie providersCookie = Request.Cookies["LoWEcatdsafion"]; if (providersCookie != null && providersCookie.HasKeys) { string location = Convert.ToString(providersCookie["Location"]); if (!string.IsNullOrEmpty(location)) { ddLocation.SelectedIndex = ddLocation.Items.IndexOf(ddLocation.Items.FindByValue(location)); } if (providersCookie["Providers"] != null) { string allProviders = Convert.ToString(providersCookie["Providers"]); string[] providers = allProviders.Split('~'); foreach (string provider in providers) { ListItem listItem = lbMAandProviders.Items.FindByText(provider.Trim()); if (listItem != null) { lbSelectedMAandProviders.Items.Add(listItem); lbMAandProviders.Items.Remove(listItem); } } } } } }
private string GetIdentity() { string id = string.Empty; if (HttpContext.Current != null) { if (HttpContext.Current.Session != null) { id = HttpContext.Current.Session.SessionID; } else if (HttpContext.Current.Request["MasterSlaveID"] != null) { id = HttpContext.Current.Request["MasterSlaveID"]; } if (string.IsNullOrEmpty(id)) { HttpCookie cookie = HttpContext.Current.Request.Cookies["MasterSlaveID"]; if (cookie != null) { id = cookie.Value; } else { id = Guid.NewGuid().ToString().Replace("-", ""); cookie = new HttpCookie("MasterSlaveID", id); cookie.Expires = DateTime.Now.AddMonths(1); HttpContext.Current.Response.Cookies.Add(cookie); } } } if (string.IsNullOrEmpty(id)) { id = DateTime.Now.Minute + Thread.CurrentThread.ManagedThreadId.ToString(); } return("MasterSlave_" + id); }
public ActionResult LogOn(LogOnModel model, string returnUrl) { Session["Notification"] = ""; if (ModelState.IsValid) { KIREIP.Core.Manager.UserManager CM = new KIREIP.Core.Manager.UserManager(); KIREIP.Core.DAL.Login usr = CM.LoginUser(model.UserName, model.Password); if (usr != null) { FormsAuthentication.Initialize(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usr.UserName.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, FormsAuthentication.FormsCookiePath); string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } Response.Cookies.Add(cookie); if ((!String.IsNullOrEmpty(returnUrl)) && returnUrl.Length > 1) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Message")); } } else { ModelState.AddModelError("", "Incorrect user name or password."); } } // If we got this far, something failed, redisplay form return(View(model)); }