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); }
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; }
public virtual void SignIn(Customer customer, bool createPersistentCookie) { var now = DateTime.UtcNow.ToLocalTime(); var ticket = new FormsAuthenticationTicket( 1 /*version*/, _customerSettings.UsernamesEnabled ? customer.Username : customer.Email, now, now.Add(_expirationTimeSpan), createPersistentCookie, _customerSettings.UsernamesEnabled ? customer.Username : customer.Email, FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.HttpOnly = true; if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } cookie.Secure = FormsAuthentication.RequireSSL; cookie.Path = FormsAuthentication.FormsCookiePath; if (FormsAuthentication.CookieDomain != null) { cookie.Domain = FormsAuthentication.CookieDomain; } _httpContext.Response.Cookies.Add(cookie); _cachedCustomer = customer; }
public ActionResult SendEmail(MessageDetails message) { HttpCookie cookie = new HttpCookie("authorEmail", message.authorEmail); Response.SetCookie(cookie); if (!ModelState.IsValid) return View("Index", message); if (Request.IsAjaxRequest()) { MessagesContext db = new MessagesContext(); db.Messages.Add(message); db.SaveChanges(); return PartialView("_PartialEmailConfirmation", message); } else { MessagesContext db = new MessagesContext(); db.Messages.Add(message); db.SaveChanges(); return RedirectToAction("EmailConfirmation", message); } }
public ActionResult LogOn(LoginModel model, string returnUrl) { ViewBag.Message = "Please enter username and password for login."; if (ModelState.IsValid) { User user = ValidateUser(model.username, model.password); if (user != null) { var authTicket = new FormsAuthenticationTicket(1, model.username, DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, "1"); string cookieContents = FormsAuthentication.Encrypt(authTicket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents) { Expires = authTicket.Expiration, Path = FormsAuthentication.FormsCookiePath }; Response.Cookies.Add(cookie); if (!string.IsNullOrEmpty(returnUrl)) Response.Redirect(returnUrl); return RedirectToAction("Index", "Dashboard"); } else { ViewBag.Message = "The user name or password provided is incorrect. Please try again"; } } // If we got this far, something failed, redisplay form return View(model); }
protected void ButtonLogin_Click(object sender, EventArgs e) { HttpCookie cookie = new HttpCookie("Username", this.TextBoxUsername.Text.Trim()); cookie.Expires = DateTime.Now.AddMinutes(1); Response.Cookies.Add(cookie); this.TextBoxUsername.Text = ""; }
protected void UserAuthenticate(object sender, AuthenticateEventArgs e) { if (Membership.ValidateUser(this.LoginForm.UserName, this.LoginForm.Password)) { e.Authenticated = true; return; } string url = string.Format( this.ForumAuthUrl, HttpUtility.UrlEncode(this.LoginForm.UserName), HttpUtility.UrlEncode(this.LoginForm.Password) ); WebClient web = new WebClient(); string response = web.DownloadString(url); if (response.Contains(groupId)) { e.Authenticated = Membership.ValidateUser("Premier Subscriber", "danu2HEt"); this.LoginForm.UserName = "******"; HttpCookie cookie = new HttpCookie("ForumUsername", this.LoginForm.UserName); cookie.Expires = DateTime.Now.AddMonths(2); Response.Cookies.Add(cookie); } }
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)) { // 使用 Cookie 中的 Anti-XSRF 令牌 _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; }
public void cookieUse(string name, string value, int day) { HttpCookie cookie = new HttpCookie(name); cookie.Value = value; cookie.Expires = DateTime.Today.AddDays(day); Response.Cookies.Add(cookie); }
/// <summary> /// �û���¼���� /// </summary> /// <param name="username">�û���</param> /// <param name="roles">�û���ɫ</param> /// <param name="isPersistent">�Ƿ�־�cookie</param> public static void Login(string username, string roles, bool isPersistent) { DateTime dt = isPersistent ? DateTime.Now.AddMinutes(99999) : DateTime.Now.AddMinutes(60); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ʊ�ݰ汾�� username, // Ʊ�ݳ����� DateTime.Now, //����Ʊ�ݵ�ʱ�� dt, // ʧЧʱ�� isPersistent, // ��Ҫ�û��� cookie roles, // �û����ݣ�������ʵ�����û��Ľ�ɫ FormsAuthentication.FormsCookiePath);//cookie��Ч·�� //ʹ�û�����machine key����cookie��Ϊ�˰�ȫ���� string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); //����֮���cookie //��cookie��ʧЧʱ������Ϊ��Ʊ��tikets��ʧЧʱ��һ�� HttpCookie u_cookie = new HttpCookie("username", username); if (ticket.IsPersistent) { u_cookie.Expires = ticket.Expiration; cookie.Expires = ticket.Expiration; } //���cookie��ҳ��������Ӧ�� HttpContext.Current.Response.Cookies.Add(cookie); HttpContext.Current.Response.Cookies.Add(u_cookie); }
public static void SetUserAndCookie(this HttpContext context, string login, bool isSetCookie = true) { if (login == null) { System.Web.Security.FormsAuthentication.SignOut(); context.User = null; } else { if (isSetCookie) { var authTicket = new System.Web.Security.FormsAuthenticationTicket ( 1, //version login, // user name DateTime.Now, //creation DateTime.Now.AddYears(50), //Expiration (you can set it to 1 month true, //Persistent login ); // additional informations var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = authTicket.Expiration; authCookie.HttpOnly = true; context.Response.SetCookie(authCookie); } context.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(login), Array<string>.Empty); } }
/// <summary> /// /// </summary> /// <param name="name"></param> /// <returns></returns> public static string GetCookieValue(string name) { HttpCookie myCookie = new HttpCookie("_languageId"); myCookie = HttpContext.Current.Request.Cookies["_languageId"]; return HttpContext.Current.Request.Cookies[name].Value; }
public static void ResetLoginSession(int MID) { MemCache.clear(); System.Web.HttpCookie hc = new System.Web.HttpCookie("Resx", string.Empty); hc.Expires = DateTime.Now.AddDays(-20); System.Web.HttpContext.Current.Response.SetCookie(hc); }
protected void Application_BeginRequest(Object sender, EventArgs e) { HttpCookie WebLang = Request.Cookies[VarCookie + ".Lang"]; if (WebLang == null) { //強制預設語系 //WebLang = new HttpCookie(VarCookie + ".Lang", "zh-TW"); if (Request.UserLanguages != null) if (Request.UserLanguages.Length > 0) WebLang = new HttpCookie(VarCookie + ".Lang", Request.UserLanguages[0]); else WebLang = new HttpCookie(VarCookie + ".Lang", System.Threading.Thread.CurrentThread.CurrentCulture.Name); else WebLang = new HttpCookie(VarCookie + ".Lang", System.Threading.Thread.CurrentThread.CurrentCulture.Name); Response.Cookies.Add(WebLang); } if (WebLang != null) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(WebLang.Value); System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(WebLang.Value); } }
private void login(string userName, string password) { Model.User userObj = Model.Repositories.UsersRepository.GetUserByCredentials(userName, password); if (userObj == null) return; int userID = userObj.ID; string userRoles = ""; foreach (Model.UserRole userRole in userObj.UserRoles) { if (userRoles == "") userRoles = userRole.ID.ToString(); else userRoles += "," + userRole.ID.ToString(); } if (userRoles == "") return; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), false, userRoles, FormsAuthentication.FormsCookiePath); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; Response.Cookies.Add(cookie); string returnUrl = Request.QueryString["ReturnUrl"]; if (String.IsNullOrEmpty(returnUrl)) returnUrl = "Default.aspx"; Response.Redirect(returnUrl); }
protected void Page_Init(object sender, EventArgs e) { // Der Code unten schützt vor XSRF-Angriffen. var requestCookie = Request.Cookies[AntiXsrfTokenKey]; Guid requestCookieGuidValue; if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue)) { // Das Anti-XSRF-Token aus dem Cookie verwenden _antiXsrfTokenValue = requestCookie.Value; Page.ViewStateUserKey = _antiXsrfTokenValue; } else { // Neues Anti-XSRF-Token generieren und im Cookie speichern _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; }
private void GetSetProperties (HttpCookie biscuit) { Assert.IsNull (biscuit.Domain, "Domain"); biscuit.Domain = String.Empty; Assert.AreEqual (DateTime.MinValue, biscuit.Expires, "Domain"); biscuit.Expires = DateTime.MaxValue; Assert.IsFalse (biscuit.HasKeys, "HasKeys"); biscuit["mono"] = "monkey"; Assert.AreEqual ("monkey", biscuit["mono"], "this"); Assert.IsNull (biscuit.Name, "Name"); biscuit.Name = "my"; Assert.AreEqual ("/", biscuit.Path, "Path"); biscuit.Path = String.Empty; Assert.IsFalse (biscuit.Secure, "Secure"); biscuit.Secure = true; Assert.IsTrue (biscuit.Value.IndexOf ("mono=monkey") >= 0, "Value"); biscuit.Value = "monkey=mono&singe=monkey"; #if NET_2_0 Assert.IsFalse (biscuit.HttpOnly, "HttpOnly"); biscuit.HttpOnly = true; #endif }
/// <summary> /// Set string to cookie /// </summary> /// <param name="CookieName"></param> /// <param name="CookieValue"></param> public void SetCookie(string CookieName, string CookieValue) { HttpCookie cookie = new HttpCookie(CookieName); cookie.Value = CookieValue; cookie.Expires = DateTime.Now.AddDays(30); HttpContext.Current.Response.Cookies.Add(cookie); }
public ActionResult SignIn(SignInViewModel logInViewModel) { if (ModelState.IsValid) { string errorMessage; User user = _accountService.ValidateUser(logInViewModel.UserName, logInViewModel.Password, out errorMessage); if (user != null) { SimpleSessionPersister.Username = user.Username; SimpleSessionPersister.Roles = user.Roles.Select(x => x.Name).ToList(); if (logInViewModel.StayLoggedIn) { FormsAuthenticationTicket formsAuthenticationTicket = new FormsAuthenticationTicket(SimpleSessionPersister.Username, true, 10080); string encrypt = FormsAuthentication.Encrypt(formsAuthenticationTicket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypt); Response.Cookies.Add(cookie); } return RedirectToAction("Index", "Feed"); } ModelState.AddModelError(string.Empty, errorMessage); } return View(); }
/// <summary> /// set http response cookies /// </summary> /// <param name="response"></param> /// <param name="companyUserSesson">if null-remove cookie</param> public void SetResponse ( HttpResponseBase response , CompanyUserSession companyUserSesson ) { if (companyUserSesson != null) { if (response.Cookies[SessionIdCookieName] == null) { HttpCookie sidCookie = new HttpCookie(SessionIdCookieName, companyUserSesson.Sid); response.Cookies.Add(sidCookie); } else { response.Cookies[SessionIdCookieName].Value = companyUserSesson.Sid; } if (response.Cookies[UserIdCookieName] == null) { HttpCookie uIdCookie = new HttpCookie(UserIdCookieName, companyUserSesson.CompanyUserId.ToString()); response.Cookies.Add(uIdCookie); } else { response.Cookies[UserIdCookieName].Value = companyUserSesson.CompanyUserId.ToString(); } } else { HttpCookie uIdCookie = new HttpCookie(UserIdCookieName, "") {Expires = DateTime.Now}; response.Cookies.Add ( uIdCookie ); HttpCookie sidCookie = new HttpCookie(SessionIdCookieName, "") {Expires = DateTime.Now}; response.Cookies.Add ( sidCookie ); } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { try { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); JavaScriptSerializer serializer = new JavaScriptSerializer(); if (authTicket.UserData == "OAuth") return; var currentUser = serializer.Deserialize<CurrentUserPrincipal>(authTicket.UserData); currentUser.SetIdentity(authTicket.Name); HttpContext.Current.User = currentUser; } } catch (Exception ex) { ErrorSignal.FromCurrentContext().Raise(ex); FormsAuthentication.SignOut(); HttpCookie oldCookie = new HttpCookie(".ASPXAUTH"); oldCookie.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(oldCookie); HttpCookie ASPNET_SessionId = new HttpCookie("ASP.NET_SessionId"); ASPNET_SessionId.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(ASPNET_SessionId); var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); Response.Redirect(urlHelper.Action(MVC.OAuth.ActionNames.SignIn, MVC.OAuth.Name)); } }
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; }
public ActionResult Login(LoginViewModel model) { string encryptedPass = Cryption.EncryptText(model.Password); //string decryptedPass = Cryption.DecryptText("PBilQKknnyuw05ks6TgWLg=="); User user = userRepo.GetUserAuth(model.Email, encryptedPass); if (user != null) { user.LastActivity = DateTime.Now; user.PublicIP = Utility.GetPublicIP(); userRepo.Save(); HttpCookie userCookie = new HttpCookie("USER", model.Email); if (model.RememberMe) userCookie.Expires = DateTime.Now.AddMonths(1); else userCookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(userCookie); return RedirectToAction("index", "dashboard"); } ViewBag.Message = "<div class='alert alert-danger'>" + " <button class='close' data-close='alert'></button>" + " <span>Kullanıcı adı/Parola geçersizdir. </span>" + " </div>"; return View(); }
protected void Page_Load(object sender, EventArgs e) { //first get the cookie on the incoming request. HttpCookie myCookie = new HttpCookie("ExhibitorCookie"); myCookie = Request.Cookies["ExhibitorCookie"]; string GUID = myCookie.Value.ToString().Replace("GUID=", ""); // Read the cookie information and display it. if (myCookie != null) {//Response.Write ("<p>" + GUID + "</p><p>" + myCookie.Value.ToString() + "</p>"); } else { Label1.Text = "not found"; } //second get the attendeeID from the URL. string AttendeeID = Request.QueryString["Attendee"]; string MessageToScreen = CommonFunctions.GetExhibitorNamebyGUID(GUID) + " has been visited by " + CommonFunctions.GetAttendeeName(AttendeeID); if (string.IsNullOrEmpty(AttendeeID)) { Label1.Text = "No Attendee...."; } else { Label1.Text = MessageToScreen; } //third, grab name of exhibitor from db using cookie //optional, grab attendees name out of the database. //log it to tblLog, exhibitor and name of attendee. CommonFunctions.eventToLogDB(MessageToScreen); }
private static HttpCookie CreateNewCookie() { var cookie = new HttpCookie(COOKIE_ID); HttpContext.Current.Response.AppendCookie(cookie); HttpContext.Current.Request.Cookies.Add(cookie); return cookie; }
public ActionResult Index(SignInModel signIn) { if (!ModelState.IsValid) return View(); // Hash password var password = CreatePasswordHash(signIn.Password); // If user found in the db var user = db.Users.FirstOrDefault(u => u.Username == signIn.Username && u.Password == password); if (user != null) { // Create cookie var cookie = new HttpCookie("User"); cookie.Values["UserName"] = signIn.Username; cookie.Values["UserId"] = user.UserId.ToString(); cookie.Values["Role"] = user.Role.RoleId.ToString(); // If remember me, keep the cookie for one year cookie.Expires.AddDays(signIn.RememberMe ? 365 : 1); HttpContext.Response.Cookies.Remove("User"); HttpContext.Response.SetCookie(cookie); return RedirectToAction("Index", "Home"); } else ModelState.AddModelError("", "The user name or password provided is incorrect."); return View(); }
public ActionResult Logout() { try { // First we clean the authentication ticket like always //required NameSpace: using System.Web.Security; FormsAuthentication.SignOut(); var c = new System.Web.HttpCookie("userID"); c.Expires = DateTime.Now.AddDays(-1); Response.Cookies.Add(c); // Second we clear the principal to ensure the user does not retain any authentication //required NameSpace: using System.Security.Principal; HttpContext.User = new GenericPrincipal(new GenericIdentity(string.Empty), null); Session.Clear(); System.Web.HttpContext.Current.Session.RemoveAll(); // Last we redirect to a controller/action that requires authentication to ensure a redirect takes place // this clears the Request.IsAuthenticated flag since this triggers a new request return(RedirectToLocal()); } catch { throw; } }
/// <summary> /// 生成登录成功的cookie等信息 /// </summary> /// <param name="user"></param> /// <param name="bl">记住则保存30天</param> public static void CreateLoginInfo(BasicInfo user, bool bl) { HttpCookie cookie = new System.Web.HttpCookie(cookiename_login); cookie["Uid"] = user.Uid.ToString(); cookie["Pwd"] = user.Pwd; cookie["NickName"] = AES.Encode(user.NickName, "iyoga"); cookie["Uphone"] = AES.Encode(user.Uphone, "Uphone"); cookie["UserType"] = user.UserType.ToString(); cookie["LoginType"] = user.LoginType.ToString(); cookie["LastIP"] = user.LastIP.ToString(); cookie["UEmail"] = AES.Encode(user.UEmail, "UEmail"); cookie["Url"] = user.Url; if (user.Avatar != null) { cookie["Avatar"] = user.Avatar.ToString(); } else { cookie["Avatar"] = ""; } cookie.HttpOnly = false; if (bl) { cookie.Expires = DateTime.Now.AddDays(30);//选择记住则保存30天 cookie["Expires"] = DateTime.Now.AddDays(30).ToString(); } else { cookie.Expires = DateTime.Now.AddDays(1);//保存一天 cookie["Expires"] = DateTime.Now.AddDays(1).ToString(); } HttpContext.Current.Response.AppendCookie(cookie); }
public void Login(FormCollection collection) { object obj = SqlHelper.ExecuteScalar("select UserId from CDBUsers where UserName=@uname and Password=@pwd", new SqlParameter("@uname", collection[0]), new SqlParameter("@pwd", Weibo.Models.Myencrypt.myencrypt(collection[1]))); if (obj != null) { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, collection[0], DateTime.Now, DateTime.Now.AddMinutes(30), false, "admins" ); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); } Response.Redirect("~/"); }
public void ClearLoginStatus() { try { System.Web.HttpCookie httpCookie = HiContext.Current.Context.Request.Cookies["Token_" + HiContext.Current.User.UserId.ToString()]; if (httpCookie != null && !string.IsNullOrEmpty(httpCookie.Value)) { httpCookie.Expires = System.DateTime.Now; System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie); } System.Web.HttpCookie httpCookie2 = HiContext.Current.Context.Request.Cookies["Vshop-Member"]; if (httpCookie2 != null && !string.IsNullOrEmpty(httpCookie2.Value)) { httpCookie2.Expires = System.DateTime.Now; System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie2); } if (System.Web.HttpContext.Current.Request.IsAuthenticated) { System.Web.Security.FormsAuthentication.SignOut(); System.Web.HttpCookie authCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(HiContext.Current.User.Username, true); IUserCookie userCookie = HiContext.Current.User.GetUserCookie(); if (userCookie != null) { userCookie.DeleteCookie(authCookie); } RoleHelper.SignOut(HiContext.Current.User.Username); System.Web.HttpContext.Current.Response.Cookies["hishopLoginStatus"].Value = ""; } } catch { } }
public ActionResult LogOut() { FormsAuthentication.SignOut(); Session.Clear(); Session.Abandon(); // replace with username if this is the wrong cookie name Response.Cookies.Remove(FormsAuthentication.FormsCookieName); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1)); Response.Cache.SetNoStore(); Response.AppendHeader("Pragma", "no-cache"); // send an expired cookie back to the browser var ticketExpiration = DateTime.Now.AddDays(-7); var ticket = new FormsAuthenticationTicket( 1, //replace with username if this is the wrong cookie name FormsAuthentication.FormsCookieName, DateTime.Now, ticketExpiration, false, String.Empty); var cookie = new System.Web.HttpCookie("user") { Expires = ticketExpiration, Value = FormsAuthentication.Encrypt(ticket), HttpOnly = true }; Response.Cookies.Add(cookie); return(RedirectToAction("Index", "Login")); }
/// <summary> /// 注销当前用户 /// </summary> public void Logout() { int accid = this.UserID; if (accid < 1) { return; } System.Web.HttpContext _context = System.Web.HttpContext.Current; if (this.LoginPattern == LoginPatternEnum.Cookies) { //如果是多机构,又不用IP访问,则用根域写入cookie int multi = Business.Do <ISystemPara>()["MultiOrgan"].Int32 ?? 0; //清理当前域名下的cookie System.Web.HttpCookie cookie = _context.Response.Cookies[KeyName]; if (cookie != null) { if (multi == 0 && !WeiSha.Common.Server.IsLocalIP) { cookie.Domain = WeiSha.Common.Server.MainName; } cookie.Expires = DateTime.Now.AddYears(-1); _context.Response.Cookies.Add(cookie); } } if (this.LoginPattern == LoginPatternEnum.Session) { _context.Session.Abandon(); } this.CleanOut(accid); }
public string Login(string username, string password, string cbox) { //身份验证 SqlDataReader obj = BookDAL.SqlHelper.ExecuteReader(BookDAL.SqlHelper.GetConnSting(), CommandType.Text, "select * from ISRegister where UserName=@UserName and PassWord =@PassWord", new SqlParameter("UserName", username.Trim()), new SqlParameter("PassWord", password.Trim())); string data; if (obj.Read()) { string role = obj["职位"].ToString(); string name = obj["姓名"].ToString(); obj.Close(); FormsAuthenticationTicket authTicket; if (cbox == "true") { //MVC票据生成 authTicket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddDays(14), false, role ); HttpCookie cookie = new HttpCookie("login"); cookie.Values.Add("uid", username.Trim()); cookie.Values.Add("name", HttpUtility.UrlEncode(name.Trim())); cookie.Expires = DateTime.Now.AddDays(14); Response.Cookies.Add(cookie); } else { { authTicket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(30), false, role ); } HttpCookie cookie = new HttpCookie("login"); cookie.Values.Add("uid", username.Trim()); cookie.Values.Add("name", HttpUtility.UrlEncode(name.Trim())); cookie.Expires = DateTime.Now.AddMinutes(30); Response.Cookies.Add(cookie); } string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); data = "1"; return(data); } else { obj.Close(); data = "0"; return(data); } }
public void RenewCurrentUser() { System.Web.HttpCookie authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = null; authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null && !authTicket.Expired) { FormsAuthenticationTicket newAuthTicket = authTicket; if (FormsAuthentication.SlidingExpiration) { newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket); } string userData = newAuthTicket.UserData; string[] roles = userData.Split(','); System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles); } } }
/// <summary> /// 用户登录成功方法 /// </summary> /// <param name="loginname">登录成功名</param> /// <param name="password">未加密密码</param> /// <param name="rememberMe">记住我开关</param> /// <param name="page">调用页面</param> /// <returns>是否登录成功</returns> public static bool UserLogOn(string account, bool rememberMe, System.Web.UI.Page page) { List <Model.Sys_User> x = (from y in Funs.DB.Sys_User where y.Account == account && y.IsPost == true select y).ToList(); if (x.Any()) { string accValue = HttpUtility.UrlEncode(account); FormsAuthentication.SetAuthCookie(accValue, false); page.Session[SessionName.CurrUser] = x.First(); if (rememberMe) { System.Web.HttpCookie u = new System.Web.HttpCookie("UserInfo"); u["username"] = accValue; //u["password"] = password; // Cookies过期时间设置为一年. u.Expires = DateTime.Now.AddYears(1); page.Response.Cookies.Add(u); } else { // 当选择不保存用户名时,Cookies过期时间设置为昨天. page.Response.Cookies["UserInfo"].Expires = DateTime.Now.AddDays(-1); } return(true); } else { return(false); } }
/// <summary> /// Process Request /// </summary> /// <param name="context">Http Context</param> public void ProcessRequest(HttpContext context) { System.Web.HttpCookie userloginname = context.Request.Cookies["UserLoginName"]; if (null != userloginname) { userloginname.Expires = DateTime.Now.AddDays(-1); if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain)) { userloginname.Domain = FormsAuthentication.CookieDomain; } System.Web.HttpContext.Current.Response.Cookies.Add(userloginname); } FormsAuthentication.SignOut(); HttpCookie auth = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName]; if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain)) { auth.Domain = FormsAuthentication.CookieDomain; } auth.Expires = DateTime.Now.AddDays(-1); System.Web.HttpContext.Current.Response.Cookies.Add(auth); context.Response.Redirect(FormsAuthentication.LoginUrl); }
protected void Page_Load(object sender, System.EventArgs e) { if (this.Context.Request.IsAuthenticated) { System.Web.Security.FormsAuthentication.SignOut(); System.Web.HttpCookie authCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(HiContext.Current.User.Username, true); IUserCookie userCookie = HiContext.Current.User.GetUserCookie(); if (userCookie != null) { userCookie.DeleteCookie(authCookie); } RoleHelper.SignOut(HiContext.Current.User.Username); } string text = base.Request.QueryString["ot"]; if (OpenIdPlugins.Instance().GetPluginItem(text) == null) { this.lblMsg.Text = "没有找到对应的插件,<a href=\"" + Globals.GetSiteUrls().Home + "\">返回首页</a>。"; return; } OpenIdSettingsInfo openIdSettings = MemberProcessor.GetOpenIdSettings(text); if (openIdSettings == null) { this.lblMsg.Text = "请先配置此插件所需的信息,<a href=\"" + Globals.GetSiteUrls().Home + "\">返回首页</a>。"; return; } string returnUrl = Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("OpenIdEntry_url", new object[] { text })); OpenIdService openIdService = OpenIdService.CreateInstance(text, HiCryptographer.Decrypt(openIdSettings.Settings), returnUrl); openIdService.Post(); }
public static void setCooki(string key, string val) { System.Web.HttpCookie httpCookie = new System.Web.HttpCookie(key); httpCookie.Value = val; httpCookie.Expires = System.DateTime.Now.AddYears(1); System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie); }
public Document WebExport( Boolean openCloseConnection, String fileName, DocTemplateVers.Domain.DTO.ServiceExport.DTO_Settings Settings, System.Web.HttpResponse webResponse, System.Web.HttpCookie cookie, IList <DocTemplateVers.Domain.DTO.ServiceExport.DTO_Signature> Signatures, String waterMark) { if (openCloseConnection) { webResponse.Clear(); } if (cookie != null) { webResponse.AppendCookie(cookie); } webResponse.AddHeader("Content-Disposition", "attachment; filename=" + HtmlCheckFileName(fileName) + "." + ExportFileType.pdf.ToString()); webResponse.ContentType = "application/pdf"; Document doc = ExportTo(Settings, webResponse.OutputStream, false, Signatures, waterMark); if (doc != null && openCloseConnection) { webResponse.End(); } return(doc); }
public void RegisterRememberLogon(IEnumerable <view_emCompanyMember> list, bool IsRemember) { Hashtable htRemember = GetRememberLogon(); if (htRemember.Count > 0) { //ทำการ Clear ข้อมูลเดิมก่อน UnRegisterRememberLogon(); } if (!IsRemember) //ถ้าไม่จำ User + Password { IsRemember = false; //กำหนดให้ไม่จำ list.First().UserName = string.Empty; } else { // Add ข้อมูล กรณีจำชื่อผู้ใช้ HttpCookie ckRememberApp = new System.Web.HttpCookie(RememberAppName); ckRememberApp.Values["IsRemember"] = IsRemember.ToString(); ckRememberApp.Values["RememberUserName"] = list.First().UserName; ckRememberApp.Values["RememberPassword"] = list.First().Password; ckRememberApp.Expires = DateTime.Now.AddYears(200); System.Web.HttpContext.Current.Response.Cookies.Add(ckRememberApp); } }
public ActionResult SetCulture(string culture, string currentUrl) { // Validate input culture = CultureHelper.GetImplementedCulture(culture); // Save culture in a cookie System.Web.HttpCookie cookie = Request.Cookies["_culture"]; if (cookie != null) { cookie.Value = culture; // update cookie value } else { cookie = new System.Web.HttpCookie("_culture") { Value = culture, Expires = DateTime.Now.AddYears(1) }; } Response.Cookies.Add(cookie); if (!string.IsNullOrWhiteSpace(currentUrl)) { return(Redirect(currentUrl)); } return(RedirectToAction("Index")); }
public ResponseModel <BasketModel> GetQuoteBasket(string quoteId, string action) { Guid basketId; Guid.TryParse(quoteId, out basketId); var result = new ResponseModel <BasketModel>(); //Get currentBasketId from cookies or by DeviceId(if cookieBasketId is null SP returns by DeviceId) and call PersistentBasket. if (action == ExistingBasket.Merge.GetHashCode().ToString()) { var currentBasketId = HttpContext.Current.Request.Cookies[Constants.COOKIE_BASKETID]?.Value.ToString(); if (String.IsNullOrEmpty(currentBasketId)) { var currentBasket = CallApi <BasketModel>(string.Format(ApiUrls.GetBasket, String.IsNullOrEmpty(currentBasketId) ? Guid.Empty.ToString() : currentBasketId), ""); currentBasketId = currentBasket.Result?.Id; } result = CallApi <BasketModel>(string.Format(ApiUrls.PersistentBasket, quoteId, currentBasketId), "", Method.POST); } //Set basketId in cookies that is quoteBasketId . var cookie_basketId = new System.Web.HttpCookie(Constants.COOKIE_BASKETID) { HttpOnly = true, Value = result.Result != null ? result.Result.Id : quoteId, Expires = DateTime.Now.AddDays(Constants.COOKIE_DEVICEID_EXPIRES_DAYS) }; System.Web.HttpContext.Current.Response.Cookies.Add(cookie_basketId); if (System.Web.HttpContext.Current.Session != null) { System.Web.HttpContext.Current.Session[Constants.SESSION_BASKET] = null; } return(CallApi <BasketModel>(string.Format(ApiUrls.GetBasket, basketId), "")); }
private void btnAdminLogin_Click(object sender, System.EventArgs e) { if (!Globals.CheckVerifyCode(this.txtCode.Text.Trim())) { this.ShowMessage("验证码不正确"); } else { ManagerInfo manager = ManagerHelper.GetManager(this.txtAdminName.Text); if (manager == null) { this.ShowMessage("无效的用户信息"); } else { if (manager.Password != HiCryptographer.Md5Encrypt(this.txtAdminPassWord.Text)) { this.ShowMessage("密码不正确"); } else { System.Web.HttpCookie cookie = new System.Web.HttpCookie("Vshop-Manager") { Value = manager.UserId.ToString(), Expires = System.DateTime.Now.AddDays(1.0) }; System.Web.HttpContext.Current.Response.Cookies.Add(cookie); this.Page.Response.Redirect("Default.aspx", true); } } } }
public ActionResult StaffLogin(string returnUrl) { Login loginModel = new Login(); if (this.Request.Cookies["SmartLibraryAD"] != null) { System.Web.HttpCookie cookie = this.Request.Cookies["SmartLibraryAD"]; loginModel.RememberMe = ConvertTo.ToBoolean(cookie.Values.Get("LoginIsRemember")); if (loginModel.RememberMe) { if (cookie.Values.Get("LoginEmail") != null) { loginModel.Email = cookie.Values.Get("LoginEmail"); } if (cookie.Values.Get("LoginPassword") != null) { loginModel.Password = EncryptionDecryption.DecryptByTripleDES(cookie.Values.Get("LoginPassword")); } } } loginModel.ReturnUrl = returnUrl; return(this.View(Views.StaffLogin, loginModel)); }
/// <summary> /// Sự kiện khi click vào nút đăng nhập /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void LinkButton1_Click(object sender, EventArgs e) { //Vì là phần login nên không sử dụng validate String strUserName = txtUserName.Text; String strPass = txtPass.Text; DataTable dt = dao.QuanLy_DAO.check_Login(strUserName, strPass);//Kiểm tra UserName và mật khẩu có trùng trong cơ sở dữ liệu không? if (dt.Columns.Count > 1) { if (cbRememberMe.Checked)// Xử lý khi nút checkBox Remember Me được tích { if (Request.Cookies["UserSetting"] == null)//Nếu không có cookie tồn tại trong client thì lưu mới { HttpCookie myCookie = new HttpCookie("UserSetting"); myCookie["UserName"] = strUserName; myCookie["Password"] = strPass; myCookie.Expires = DateTime.Now.AddDays(1d); Response.Cookies.Add(myCookie); } } //Tạo session cho phiên làm việc của người dùng Session["Username"] = dt.Rows[0][0].ToString(); Session["password"] = dt.Rows[0][3].ToString(); Session["isAdmin"] = dt.Rows[0][2].ToString(); Session["Name"] = dt.Rows[0][1].ToString(); Response.Redirect("index.aspx"); } else { lbHienThi.ForeColor = System.Drawing.Color.Red; lbHienThi.Text = "Khong thanh cong! Xin thử lại tên tài khoản hoặc mật khẩu."; txtUserName.Focus(); } }
public ActionResult Login(LoginModel model) { if (string.IsNullOrEmpty(model.UserName) || string.IsNullOrEmpty(model.Password)) { Response.Write("<script>alert('用户名或密码不能为空!')</script>"); return(View()); } else { BowntDAL.BowntdbEntities dal = new BowntDAL.BowntdbEntities(); if (dal.tb_SysUser.FirstOrDefault(a => a.UserName == model.UserName && a.Password == model.Password) != null) { //Session["UserName"] = model.UserName; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), false, "admins" ); string encryptedTicket = FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie authCookie = new System.Web.HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); return(RedirectToAction("Edit")); } else { Response.Write("<script>alert('用户名或密码不正确!')</script>"); } } return(View("login")); }
private void SetAddonCookie() { var navData = Request.QueryString["nav-data"]; var cookie = new HttpCookie("appharbor-nav-data", navData); Response.SetCookie(cookie); }
public static UsuarioLogin recuperaCookie() { try { System.Web.HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["UsuarioAdmin"]; if (cookie == null) { return(new UsuarioLogin()); } else { var usuario = new UsuarioLogin { idAdministrador = Convert.ToInt32(cookie.Value.Split('&')[0].Split('=')[1]), dsNome = HttpContext.Current.Server.UrlDecode(cookie.Value.Split('&')[1].Split('=')[1]), dsEmail = cookie.Value.Split('&')[2].Split('=')[1], dsLogin = cookie.Value.Split('&')[3].Split('=')[1], idTipo = Convert.ToInt16(cookie.Value.Split('&')[4].Split('=')[1]), dsTipo = cookie.Value.Split('&')[5].Split('=')[1], dsSenha = HttpContext.Current.Server.UrlDecode(cookie.Value.Split('&')[6].Split('=')[1]) }; return(usuario); } } catch { } return(new UsuarioLogin()); }
/// <summary> /// 删除指定名称的Cookie /// </summary> /// <param name="name">Cookie名称</param> public static void DeleteCookie(string name) { HttpCookie cookie = new HttpCookie(name); cookie.Expires = DateTime.Now.AddYears(-1); HttpContext.Current.Response.AppendCookie(cookie); }
private void btnConfirm_Click(object sender, System.EventArgs e) { PaymentModeInfo paymentMode = SubsiteStoreHelper.GetPaymentMode(this.paymentModeId); InpourRequestInfo inpourRequestInfo = new InpourRequestInfo { InpourId = this.GenerateInpourId(), TradeDate = System.DateTime.Now, InpourBlance = this.balance, UserId = Hidistro.Membership.Context.HiContext.Current.User.UserId, PaymentId = paymentMode.ModeId }; if (SubsiteStoreHelper.AddInpourBalance(inpourRequestInfo)) { string attach = ""; System.Web.HttpCookie httpCookie = Hidistro.Membership.Context.HiContext.Current.Context.Request.Cookies["Token_" + Hidistro.Membership.Context.HiContext.Current.User.UserId.ToString()]; if (httpCookie != null && !string.IsNullOrEmpty(httpCookie.Value)) { attach = httpCookie.Value; } string text = inpourRequestInfo.InpourId.ToString(System.Globalization.CultureInfo.InvariantCulture); PaymentRequest paymentRequest = PaymentRequest.CreateInstance(paymentMode.Gateway, HiCryptographer.Decrypt(paymentMode.Settings), text, inpourRequestInfo.InpourBlance + paymentMode.CalcPayCharge(inpourRequestInfo.InpourBlance), "预付款充值", "操作流水号-" + text, Hidistro.Membership.Context.HiContext.Current.User.Email, inpourRequestInfo.TradeDate, Globals.FullPath(Globals.GetSiteUrls().Home), Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("DistributorInpourReturn_url", new object[] { paymentMode.Gateway })), Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("DistributorInpourNotify_url", new object[] { paymentMode.Gateway })), attach); paymentRequest.SendRequest(); } }
public void Login(object sender, System.EventArgs e) { try { ActiveUp.Net.Mail.Imap4Client imap4Client = new ActiveUp.Net.Mail.Imap4Client(); imap4Client.Connect((string)Application["server\uFFFD"], System.Convert.ToInt32(Application["port\uFFFD"])); System.Web.Security.FormsAuthentication.SetAuthCookie(iLogin.Text + "|\uFFFD" + iPassword.Text, false); imap4Client.Login(iLogin.Text, iPassword.Text); Session.Add("login\uFFFD", iLogin.Text); Session.Add("imapobject\uFFFD", imap4Client); System.Web.HttpCookie httpCookie = new System.Web.HttpCookie("login\uFFFD", iLogin.Text); System.DateTime dateTime = System.DateTime.Now; httpCookie.Expires = dateTime.AddMonths(2); Response.Cookies.Add(httpCookie); Visible = false; EnableViewState = false; // ((_Default)Page).SetWebmailLanguage(null, null); //BoundMailboxContent.BoundTopNavigation.Enable(); //BoundMailboxContent.BoundTree.LoadTrees(); //BoundMailboxContent.BoundTopNavigation.LoadList(); //BoundMailboxContent.LoadMailbox(Application["startfolder\uFFFD"].ToString(), true); } catch (System.Exception e1) { Visible = true; EnableViewState = true; iLogin.Text = System.String.Empty; // Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + Language.Get(Server.MapPath("languages/\uFFFD"), Application["defaultlanguage\uFFFD"].ToString()).Words[96].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e1.Message + e1.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD"); Page.RegisterStartupScript("ShowError\uFFFD", "<script>ShowErrorDialog('\uFFFD" + Language.Get(Server.MapPath("languages/"), Application["defaultlanguage\uFFFD"].ToString()).Words[96].ToString() + "','\uFFFD" + System.Text.RegularExpressions.Regex.Escape(e1.Message + e1.StackTrace).Replace("'\uFFFD", "\\'\uFFFD") + "');</script>\uFFFD"); } }
public static string GetCookie(string CookieName) { string result = "0"; try { if (System.Web.HttpContext.Current.Request.Cookies[CookieName] != null) { System.Web.HttpCookie IMCookie = System.Web.HttpContext.Current.Request.Cookies[CookieName]; // IMCookie.Domain = ""; DateTime endDate = DateTime.Parse(EncrypManager.Decode(IMCookie["e"])); // DateTime endDate = DateTime.Parse(IMCookie["e"]); if (endDate > DateTime.Now) { RemoveCookie(CookieName); System.Web.HttpCookie NewDiyCookie = new System.Web.HttpCookie(CookieName); // NewDiyCookie.Domain = ""; NewDiyCookie.Values.Add("obj", IMCookie["obj"]); NewDiyCookie.Values.Add("e", EncrypManager.Encode(DateTime.Now.AddMinutes(LoginExpirationIntervalMinutes).ToString()));//存储到期时间 System.Web.HttpContext.Current.Response.AppendCookie(NewDiyCookie); result = EncrypManager.Decode(IMCookie["obj"]); // result = IMCookie["obj"]; } } } catch (Exception ex) { ServerLogger.Error(ex.Message); } return(result); }
protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); System.Web.HttpCookie httpCookie = HiContext.Current.Context.Request.Cookies["Token_" + HiContext.Current.User.UserId.ToString()]; if (httpCookie != null && !string.IsNullOrEmpty(httpCookie.Value)) { httpCookie.Expires = System.DateTime.Now; System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie); } System.Web.HttpCookie httpCookie2 = HiContext.Current.Context.Request.Cookies["Vshop-Member"]; if (httpCookie2 != null && !string.IsNullOrEmpty(httpCookie2.Value)) { httpCookie2.Expires = System.DateTime.Now; System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie2); } if (this.Context.Request.IsAuthenticated) { System.Web.Security.FormsAuthentication.SignOut(); System.Web.HttpCookie authCookie = System.Web.Security.FormsAuthentication.GetAuthCookie(HiContext.Current.User.Username, true); IUserCookie userCookie = HiContext.Current.User.GetUserCookie(); if (userCookie != null) { userCookie.DeleteCookie(authCookie); } RoleHelper.SignOut(HiContext.Current.User.Username); this.Context.Response.Cookies["hishopLoginStatus"].Value = ""; } HiCache.Remove("DataCache-UserLookuptable"); this.Context.Response.Redirect(Globals.GetSiteUrls().Home, true); }
public static string getCookie(string cookie_name, string key_name) { try { System.Web.HttpCookie cookie = HttpContext.Current.Request.Cookies[cookie_name]; string val = ""; if (cookie != null) { val = (!String.IsNullOrEmpty(cookie_name)) ? cookie[key_name] : cookie.Value; if (!String.IsNullOrEmpty(val)) { return(Uri.UnescapeDataString(val)); } else { return(""); } } else { return(""); } } catch (Exception ex) { throw ex; } }
/// <summary> /// 注销当前用户 /// </summary> public void Logout() { int accid = this.CurrentUserId; if (accid < 1) { return; } System.Web.HttpContext _context = System.Web.HttpContext.Current; //登录标识名 string key = WeiSha.Common.Login.Get["Accounts"].KeyName.String; if (Accounts.LoginPattern == LoginPatternEnum.Cookies) { System.Web.HttpCookie cookie = _context.Response.Cookies[key]; if (cookie != null) { if (!WeiSha.Common.Server.IsLocalIP) { cookie.Domain = WeiSha.Common.Request.Domain.MainName; } cookie.Expires = DateTime.Now.AddYears(-1); _context.Response.Cookies.Add(cookie); } } if (Accounts.LoginPattern == LoginPatternEnum.Session) { _context.Session.Abandon(); } }
public ActionResult LoginMe(Login log) { try { var cusData = JsonConvert.SerializeObject(log); var client = new RestClient("http://wingsofpride619-001-site1.btempurl.com/api/Login/GetLogin"); client.Timeout = -1; var request = new RestRequest(Method.POST); request.AddHeader("Content-Type", "application/json"); request.AddParameter("application/json", cusData, ParameterType.RequestBody); IRestResponse response = client.Execute(request); var res = response.Content; dynamic jsonresult = JsonConvert.DeserializeObject <dynamic>(res); if (jsonresult.response == "1") { var fullname_cookie = new System.Web.HttpCookie("userID"); fullname_cookie.Value = log.username; fullname_cookie.Expires = DateTime.Now.AddDays(1); Response.Cookies.Add(fullname_cookie); return(Json(response.Content, JsonRequestBehavior.AllowGet)); } else { return(Json(response.Content, JsonRequestBehavior.AllowGet)); } } catch (Exception ex) { var cusData = JsonConvert.SerializeObject(ex); return(Json(cusData, JsonRequestBehavior.AllowGet)); } }
public static HttpCookie GetAndCreateCookies(string Name) { HttpCookie cookie = HttpContext.Current.Request.Cookies[Name]; if (cookie == null) cookie = new HttpCookie(Name); return cookie; }
public void OnAuthenticateRequest(Object source, EventArgs args) { //custom Authentication logic can go here var app = source as HttpApplication; HttpRequest req = app.Context.Request; HttpResponse rep = app.Context.Response; //empty cookie goes to Login if (req.Cookies.Count == 0) { //set temp cookie string publicName = "public"; HttpCookie c = new HttpCookie("public", publicName); c.Expires = DateTime.Now.AddMinutes(30); HttpContext.Current.Response.Cookies.Add(c); HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("public"), new[] { "public" }); //redirect to base rep.Redirect("/"); } //get cookie HttpCookie cookie = req.Cookies["user"]; if (cookie != null) { //desencriptacao string userName = cookie.Value; MembershipUser user = IndividualRepository.Instance.GetUser(userName, true); //User u = UserLocator.findUser(userName); if (user != null) HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(userName), ((Individual.Individual)user).getRoles()); } }
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; }
private void AddAlert(string alertStyle, string message, bool dismissable) { string value = System.Web.HttpUtility.UrlEncode(alertStyle + '|' + message + '|' + dismissable.ToString()); System.Web.HttpCookie cookie = System.Web.HttpContext.Current.Response.Cookies[Alert.CookieMessageKey]; cookie.Values.Add(Alert.CookieMessageKey + (cookie.Values.Count + 1).ToString("00"), value); }