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); } }
public static void SetAuthCookie(this HttpResponseMessage response, string login) { if (login == null) { var authCookie = new CookieHeaderValue(System.Web.Security.FormsAuthentication.FormsCookieName, ""); authCookie.Expires = DateTime.UtcNow.AddDays(-1); authCookie.HttpOnly = true; response.Headers.AddCookies(new[] { authCookie }); } else { 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 CookieHeaderValue(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = authTicket.Expiration; authCookie.HttpOnly = true; response.Headers.AddCookies(new[] { authCookie }); } }
public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this.ticket = ticket; this.UserName = ticket.Name; char[] delimiterChars = { ';' }; string[] userData = ticket.UserData.Split(delimiterChars); if (userData.Length == 1) { this.UserKey = ticket.UserData; this.UserID = -1; } else if (userData.Length >= 2) { this.UserKey = userData[0]; try { this.UserID = Convert.ToInt32(userData[1]); } catch (Exception) { this.UserID = -1; } } }
public ActionResult Login(RegisterUser user, string returnUrl) { var result = accountService.VaildUser(user.Email, user.Password); if (result.isSuccess) { //创建验证票subdomain share cookie var ticket = new System.Web.Security.FormsAuthenticationTicket(user.Email, true, 30); string authTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, authTicket); cookie.Domain = AppSettings.FormDomain; var userExtend = accountService.GetUserExtendInfo(user.Email); Session[user.Email] = userExtend.NickName == null ? "" : userExtend.NickName; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } else { ViewBag.Error = result.ResultMsg; } return(View()); }
public static void SetAuthCookie(this HttpResponseMessage response, string login) { if (login == null) { var authCookie = new CookieHeaderValue(System.Web.Security.FormsAuthentication.FormsCookieName, ""); authCookie.Expires = DateTime.UtcNow.AddDays(-1); authCookie.HttpOnly = true; response.Headers.AddCookies(new[] { authCookie }); } else { 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 CookieHeaderValue(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = authTicket.Expiration; authCookie.HttpOnly = true; response.Headers.AddCookies(new[] { authCookie }); } }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // 这不会计入到为执行帐户锁定而统计的登录失败次数中 // 若要在多次输入错误密码的情况下触发帐户锁定,请更改为 shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout : false); switch (result) { case SignInStatus.Success: System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(model.Email, true, 60); string ticketStr = System.Web.Security.FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, ticketStr)); return(RedirectToLocal(returnUrl)); case SignInStatus.LockedOut: return(View("Lockout")); case SignInStatus.RequiresVerification: return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe })); case SignInStatus.Failure: default: ModelState.AddModelError("", "无效的登录尝试。"); return(View(model)); } }
public virtual void SignIn(User user, bool createPersistentCookie) { var now = DateTime.Now; var ticket = new System.Web.Security.FormsAuthenticationTicket( 1, user.Account, now, now.Add(System.Web.Security.FormsAuthentication.Timeout), createPersistentCookie, user.Account, System.Web.Security.FormsAuthentication.FormsCookiePath); var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); var userName = HttpUtility.UrlEncode(user.Account); var userNameCookie = new HttpCookie("userName", userName); cookie.HttpOnly = true; if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; userNameCookie.Expires = ticket.Expiration; } cookie.Secure = System.Web.Security.FormsAuthentication.RequireSSL; cookie.Path = System.Web.Security.FormsAuthentication.FormsCookiePath; if (System.Web.Security.FormsAuthentication.CookieDomain != null) { cookie.Domain = System.Web.Security.FormsAuthentication.CookieDomain; userNameCookie.Domain = System.Web.Security.FormsAuthentication.CookieDomain; } this.HttpContext.Response.Cookies.Add(cookie); this.HttpContext.Response.Cookies.Add(userNameCookie); }
/// <summary> /// Método acionado quando for iniciada um requisição. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnBeginRequest(object sender, EventArgs e) { var application = (System.Web.HttpApplication)sender; var request = application.Context.Request; var ticketText = GetTicketText(request.Cookies); if (!string.IsNullOrEmpty(ticketText)) { System.Web.Security.FormsAuthenticationTicket ticket = null; try { ticket = System.Web.Security.FormsAuthentication.Decrypt(ticketText); } catch (Exception) { } if (ticket != null && !ticket.Expired) { var ticketId = GetTicketId(request.Cookies); application.Context.Items[FormsAuthenticationTicketKey] = ticket; } } var tokenProvider = Colosoft.Security.Tokens.Provider; if (tokenProvider is Colosoft.Security.ITokenProviderExtension) { ((Colosoft.Security.ITokenProviderExtension)tokenProvider).TokenInserted += TokenInserted; } }
//public void SignIn(Models.User user, bool createPersistentCookie) public void SignIn() { //var authTicket = new System.Web.Security.FormsAuthenticationTicket(1, // user.GetFullName(), DateTime.Now, // DateTime.Now.AddMinutes(60), // createPersistentCookie, // user.UserId.ToString()); var authTicket = new System.Web.Security.FormsAuthenticationTicket(1, "Manuel Martínez", DateTime.Now, DateTime.Now.AddMinutes(60), true, "mamrtineza"); var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket); var authCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); //if (createPersistentCookie) //{ // authCookie.Expires = authTicket.Expiration; //} authCookie.Expires = authTicket.Expiration; HttpContext.Current.Response.Cookies.Add(authCookie); }
public ActionResult Login(RegisterUser user, string returnUrl) { var result = accountService.VaildUser(user.Email, user.Password); if (result.isSuccess) { //创建验证票subdomain share cookie var ticket = new System.Web.Security.FormsAuthenticationTicket(user.Email, true, 30); string authTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, authTicket); cookie.Domain = AppSettings.FormDomain; var userExtend = accountService.GetUserExtendInfo(user.Email); Session[user.Email] = userExtend.NickName == null ? "" : userExtend.NickName; Response.Cookies.Add(cookie); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return Redirect(returnUrl); } else { return RedirectToAction("Index", "Home"); } } else { ViewBag.Error = result.ResultMsg; } return View(); }
private static void SetFormsCookie(User user, bool isCookiePersistent) { // Create the authentication ticket System.Web.Security.FormsAuthenticationTicket authTicket = new System.Web.Security.FormsAuthenticationTicket(1, user.EmailAddress, // Currently name = email address DateTime.UtcNow, DateTime.UtcNow.AddYears(1), //UNDONE: HOW LONG SHALL THIS BE VALID? isCookiePersistent, user.Index.ToString() + "|" + user.Id.ToString()); // Now encrypt the ticket. string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted ticket to the // cookie as data. System.Web.HttpCookie authCookie = new System.Web.HttpCookie( System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = DateTime.UtcNow.AddYears(1); // Add the cookie to the outgoing cookies collection. System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); }
public ActionResult Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } if(!System.Web.Security.FormsAuthentication.Authenticate(model.UserName, model.Password)) { ModelState.AddModelError("", "Invalid login attempt."); return View(model); } var roleList = new List<string>(); var physician = physicianSvc.GetPhysician(model.UserName); if (physician != null) { roleList.Add("physician"); } var patient = PatientSvc.GetPatientByUserName(model.UserName); if (patient != null) { roleList.Add("patient"); } string roles = string.Join(",", roleList); var authTicket = new System.Web.Security.FormsAuthenticationTicket( 1, model.UserName, //user id DateTime.Now, DateTime.Now.AddMinutes(System.Web.Security.FormsAuthentication.Timeout.Minutes), model.RememberMe, roles, "/"); HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, System.Web.Security.FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(cookie); return RedirectToLocal(returnUrl); }
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); } }
//Восстановление авторизацию из куков. если удачно вернет true private static bool RebuildAuthOfCookie(HttpRequest reguest) { HttpCookie cookie = reguest.Cookies["MiniForumCookieName"]; if (cookie != null) { System.Web.Security.FormsAuthenticationTicket authTicket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value); int userID; //ИД пользователя из куков bool tryParseIdToInt = Int32.TryParse(authTicket.Name, out userID); if (tryParseIdToInt) { UserDAL userdal = new UserDAL(); Entities.User users = userdal.UserAuthenticationDB(userID); if (users != null) { SessionManager.SessionAuthUser(users); return(true); } else { return(false); } } else { return(false); } } return(false); }
protected void Page_Load(object sender, EventArgs e) { try { HttpCookie cookie = Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]; if (null != cookie && !string.IsNullOrEmpty(cookie.Value)) { System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value); zxpUD = ZXPUserData.DeserializeZXPUserData(ticket.UserData); } else { Response.BufferOutput = true; // Response.Redirect("/Account/Login.aspx?ReturnURL=/Default.aspx", false); mi4 url Response.Redirect("Account/Login.aspx?ReturnURL=~/Default.aspx", false);//zxp live url } } catch (Exception ex) { string strErr = " Exception Error in Default Page_Load(). Details: " + ex.ToString(); ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error); System.Web.HttpContext.Current.Session["ErrorNum"] = 1; ErrorLogging.sendtoErrorPage(1); } }
protected void Page_Load(object sender, EventArgs e) { try { HttpCookie cookie = Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]; if (null != cookie && !string.IsNullOrEmpty(cookie.Value)) { System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value); ZXPUserData zxpUD = ZXPUserData.GetZXPUserDataFromCookie(); zxpUD = ZXPUserData.DeserializeZXPUserData(ticket.UserData); if (!(zxpUD._isAdmin || zxpUD._isDockManager || zxpUD._isLoader || zxpUD._isYardMule)) //make sure this matches whats in Site.Master and Default { Response.BufferOutput = true; Response.Redirect("ErrorPage.aspx?ErrorCode=5", false); //zxp live url } } else { Response.BufferOutput = true; Response.Redirect("Account/Login.aspx?ReturnURL=~/loaderMobile.aspx", false);//zxp live url } } catch (SqlException excep) { string strErr = " SQLException Error in loaderMobile Page_Load(). Details: " + excep.ToString(); ErrorLogging.LogErrorAndRedirect(2, strErr); } catch (Exception ex) { string strErr = " Exception Error in loaderMobile Page_Load(). Details: " + ex.ToString(); ErrorLogging.LogErrorAndRedirect(1, strErr); } }//page_load()
public static ZXPUserData GetZXPUserDataFromCookie() { ZXPUserData zxpUD = new ZXPUserData(); try { HttpCookie cookie = HttpContext.Current.Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]; if (null != cookie) { if (!string.IsNullOrEmpty(cookie.Value)) { System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(cookie.Value); zxpUD = ZXPUserData.DeserializeZXPUserData(ticket.UserData); } } } catch (Exception ex) { string strErr = " Exception Error in ZXPUserData GetZXPUserDataFromCookie(). Details: " + ex.ToString(); ErrorLogging.WriteEvent(strErr, EventLogEntryType.Error); System.Web.HttpContext.Current.Session["ErrorNum"] = 1; throw; } return(zxpUD); }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext ctx = app.Context; //获取本次Http请求的HttpContext对象 if (ctx.User != null) { #region 每次请求的请求信息写入日志 string msg = string.Format(@"{0} URL:{1} REFER:{2} USER:{3} 用户IP:{4} ", "请求信息======", ctx.Request.Url.ToString(), ctx.Request.UrlReferrer != null ? ctx.Request.UrlReferrer.ToString() : "NULL", ctx.User.Identity.IsAuthenticated ? ctx.User.Identity.Name : "NOT AUTH", ctx.Request.UserHostAddress); logger.Debug(msg); #endregion if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 string userData = ticket.UserData; // logger.Debug("从UserData中恢复role信息=====" + userData); string[] roles = userData.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //将角色数据转成字符串数组,得到相关的角色信息 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了 } } }
/// <summary> /// 注册用户 /// </summary> /// <param name="user">用户注册模型</param> /// <returns>View</returns> public ActionResult Register(RegisterUser user) { if (user != null && user.PasswordQuestion != null) { if (user.PasswordQuestion == "请选择密保查询问题") { ViewBag.PasswordQuestion = "请选择一个密保查询问题"; } } if (!ModelState.IsValid || user == null || user.VerificationCode == null || user.Email == null || Session["PictureCode"] == null) { return(View("Register", user)); } if (string.Compare(user.VerificationCode, Session["PictureCode"].ToString(), true) != 0) { ViewBag.VerificationCode = "验证码错误,请重试"; return(View("Register", user)); } var membershipuser = new Membership(); membershipuser.Users = new Users(); membershipuser.Users.UserName = user.Email; membershipuser.MobilePIN = user.Mobile; membershipuser.Email = user.Email; membershipuser.Password = user.Password; var other = new OtherInformation(); other.Address = ""; other.Mobile = user.Mobile; other.QQ = user.QQ; other.Sex = SexCatalog.Male; other.NickName = user.NickName; other.PasswordQuestion = user.PasswordQuestion; other.PasswordAnswer = user.PasswordAnswer; var entityResult = accountService.AddUser(membershipuser, other); if (entityResult.isSuccess) { // 跳转到登录页面 //System.Web.Security.FormsAuthentication.SetAuthCookie(user.Email, true); //Session[user.Email] = user.NickName == null ? "" : user.NickName; var ticket = new System.Web.Security.FormsAuthenticationTicket(user.Email, true, 30); string authTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, authTicket); cookie.Domain = AppSettings.FormDomain; var userExtend = accountService.GetUserExtendInfo(user.Email); Session[user.Email] = userExtend.NickName == null ? "" : userExtend.NickName; Response.Cookies.Add(cookie); gloCache.UserCountAdd(); return(RedirectToAction("Index", "Home")); } else { ViewBag.Error = entityResult.ResultMsg; return(View("Register", user)); } }
public NerdIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this.ticket = ticket; var userData = ticket.UserData.Split('|'); if(userData.Length != 2) return; friendlyName = userData[0]; userId = new Guid(userData[1]); }
public UserModel(System.Web.Security.FormsAuthenticationTicket ticket) { try { string[] userDetails = ticket.UserData.Split(new char[] { ';' }, StringSplitOptions.None); var ids = ticket.Name.Split('_'); Id = int.Parse(ids[0]); IdNumber = ids[1]; try { if (!String.IsNullOrEmpty(userDetails[0])) { LastPasswordUpdate = long.Parse(userDetails[0]); } } catch (Exception) { LastPasswordUpdate = null; } UserRole = (UserRole)Enum.Parse(typeof(UserRole), userDetails[1]); LastName = userDetails[2]; FirstName = userDetails[3]; if (!String.IsNullOrEmpty(userDetails[4])) { Area = (Area)Enum.Parse(typeof(Area), userDetails[4]); } else { Area = null; } if (!String.IsNullOrEmpty(userDetails[5])) { UpdateTime = userDetails[5].ToDateFromUtc(); } else { UpdateTime = DateTime.MinValue; } } catch (Exception ex) { ILog _logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); _logger.Error(string.Format("error creating login details model from authentication ticket: {0}", ex)); Id = -1; } }
public static string GetURL(HttpContext context) { string key = context.Request["key"]; if (!string.IsNullOrEmpty(key)) { if (key.ToLower().StartsWith("http://") || key.ToLower().StartsWith("https://")) { return(key); } if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["DES"])) { string sKey = "saasyy20"; byte[] inputByteArray = Convert.FromBase64String(key); using (DESCryptoServiceProvider des = new DESCryptoServiceProvider()) { des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); System.IO.MemoryStream ms = new System.IO.MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(inputByteArray, 0, inputByteArray.Length); cs.FlushFinalBlock(); cs.Close(); } string str = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return(str); } } else { try { System.Web.Security.FormsAuthenticationTicket ticket = System.Web.Security.FormsAuthentication.Decrypt(key); if (ticket != null) { return(ticket.Name); } else { return(key); } } catch (Exception ex) { LogHelper.WriteError("Foresight.Web.WebUtil", "Decrpty URL fail.", ex); return(null); } } } else { return(null); } }
public ActionResult Login(LoginModel model) { try { if (ModelState.IsValid) { BLLAccess _bllAccess = new BLLAccess(); GetEmployeeAccessModel _employeeAccess = new GetEmployeeAccessModel(); _bllAccess.idno = model.IDNO; _employeeAccess = _bllAccess.GetEmployeeAccess(); if (_employeeAccess.IsLocked) { ModelState.AddModelError("", "Your account is locked. Please contact your System Administrator."); return View(); } if (!_bllAccess.VerifyUser(model.Password, _employeeAccess.PasswordHash, _employeeAccess.PasswordSalt)) { ModelState.AddModelError("", "User and/or password is incorrect."); return View(); } string _userData = Newtonsoft.Json.JsonConvert.SerializeObject(_employeeAccess); System.Web.Security.FormsAuthenticationTicket authTicket = new System.Web.Security.FormsAuthenticationTicket( 1, _employeeAccess.IDNO, System.DateTime.Now, System.DateTime.Now.AddMinutes(15), false, _userData); string encTicket = System.Web.Security.FormsAuthentication.Encrypt(authTicket); System.Web.HttpCookie faCookie = new System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); _bllAccess.UpdateLoginCountAndDate(model.IDNO); return RedirectToAction("Index", "DTR"); } else { return View(); } } catch { ModelState.AddModelError("", "User and/or password is incorrect."); return View(); } }
/// <summary> /// Generate an authentication token (.ROCK Cookie) for the given username. /// </summary> /// <param name="username">The username whose token should be generated for.</param> /// <returns>A string that represents the user's authentication token.</returns> public static string GetAuthenticationToken(string username) { var ticket = new System.Web.Security.FormsAuthenticationTicket(1, username, RockDateTime.Now, RockDateTime.Now.Add(System.Web.Security.FormsAuthentication.Timeout), true, username.StartsWith("rckipid=").ToString()); return(System.Web.Security.FormsAuthentication.Encrypt(ticket)); }
public NerdIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this.ticket = ticket; var userData = ticket.UserData.Split('|'); if (userData.Length != 2) { return; } friendlyName = userData[0]; userId = new Guid(userData[1]); }
private static void SetAuthenticationTicket(UserClass uc, int version) { System.Web.Security.FormsAuthentication.Initialize(); //The AddMinutes determines how long the user will be logged in after leaving //the site if he doesn't log off. StringBuilder sb = new StringBuilder(); sb.AppendFormat("fn={0};un={1};pi={2}", uc.FullName, uc.Username, uc.ProfileImage ); DateTime currDate = DateTime.Now; System.Web.Security.FormsAuthenticationTicket fat = new System.Web.Security.FormsAuthenticationTicket(version, uc.Username, currDate, currDate.AddMinutes(30), false, sb.ToString()); System.Web.HttpContext.Current.Response.Cookies.Add(new System.Web.HttpCookie( System.Web.Security.FormsAuthentication.FormsCookieName, System.Web.Security.FormsAuthentication.Encrypt(fat))); }
public ActionResult Login(Castellano.Web.UI.Models.Home.Login model) { if (!this.ModelState.IsValid) { return(this.View(model)); } string textoRun = model.Run.Replace(".", string.Empty).Replace("-", string.Empty); int runCuerpo = int.Parse(textoRun.Substring(0, textoRun.Length - 1)); char runDigito = char.Parse(textoRun.Replace(runCuerpo.ToString(), string.Empty)); Castellano.Persona persona = Castellano.Persona.Get(runCuerpo, runDigito); Castellano.Membresia.LoginStatus loginStatus = Castellano.Membresia.Account.DoLogin(persona, model.Password); if (loginStatus == Castellano.Membresia.LoginStatus.InvalidRunOrPassword) { this.ModelState.AddModelError("loginError", "R.U.N. o contraseña incorrectos. Verifique sus datos e inténte acceder nuevamente."); return(this.View(model)); } else if (loginStatus == Castellano.Membresia.LoginStatus.NotAccessAllowed) { this.ModelState.AddModelError("loginError", "Usted no tiene suficientes permisos para ingresar a la aplicación. Por favor contacte al administrador."); return(this.View(model)); } else if (loginStatus == Castellano.Membresia.LoginStatus.UserApprovedOut) { this.ModelState.AddModelError("loginError", "Su cuenta de acceso a sido caducada. Por favor contacte al administrador del sistema."); return(this.View(model)); } else if (loginStatus == Castellano.Membresia.LoginStatus.UserLocked) { this.ModelState.AddModelError("loginError", "Su cuenta de acceso a sido bloqueada por exceder el máximo de intentos fallidos permitidos."); return(this.View(model)); } System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, persona.Id.ToString(), DateTime.Now, DateTime.Now.AddYears(1), model.RememberMe, "CASTELLANO_AUTHENTICATE"); string cookie = System.Web.Security.FormsAuthentication.Encrypt(ticket); HttpCookie httpCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, cookie); System.Web.Security.FormsAuthentication.SetAuthCookie(persona.Id.ToString(), model.RememberMe); this.Response.Cookies.Add(httpCookie); return(this.RedirectToAction("Index", "Admin", new { area = "Administracion" })); }
private void SignInUser(string userName, string userData, bool createPersistentCookie) { //保存到Cookie //FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); var ticket = new System.Web.Security.FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddYears(5), false, userData); string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); var authCookie = new System.Web.HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.HttpOnly = true; System.Web.HttpContext.Current.Response.Cookies.Set(authCookie); //string url = FormsAuthentication.GetRedirectUrl("username", false); //Response.Redirect(url); }
public static string GetLoginUserGuid() { var guid = ""; HttpCookie authCookie = HttpContext.Current.Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]; if (authCookie != null) { System.Web.Security.FormsAuthenticationTicket authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value); guid = authTicket.UserData; } return(guid); }
protected static string UserRoles() { string roles = null; if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 string userData = ticket.UserData; //从UserData中恢复role信息 roles = userData; //userData.Split(','); //将角色数据转成字符串数组,得到相关的角色信息 } } return(roles); }
/// <summary> /// 存储用户公共信息 /// </summary> /// <param name="ticket"></param> /// <returns></returns> public virtual User GetAuthenticatedCustomerFromTicket(System.Web.Security.FormsAuthenticationTicket ticket) { if (ticket == null) { throw new ArgumentNullException("ticket"); } var usernameLoginAccount = ticket.UserData; if (string.IsNullOrWhiteSpace(usernameLoginAccount)) { return(null); } var user = this._userRepository.FindUser(t => t.Account == usernameLoginAccount); return(user); }
protected static int UserID() { int userID = 0; if (HttpContext.Current.User != null) { if (HttpContext.Current.User.Identity.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 userID = int.Parse(ticket.Name); } } //return userID; //程序调试阶段默认userid=3 return(3); }
public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket) : base(ticket) { if (ticket.UserData != null && ticket.UserData.IndexOf("|") != -1) { string[] dataSections = ticket.UserData.Split('|'); //Get the first name FirstName = dataSections.Length >= 3 ? dataSections[2] : ""; //Get the username UserName = ticket.Name; #region Parse the UserID int userID = 0; int.TryParse(dataSections[0], out userID); this.UserID = userID; #endregion this.Roles = System.Text.RegularExpressions.Regex.Split(dataSections[1], ","); } }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; HttpContext ctx = app.Context; //获取本次Http请求的HttpContext对象 if (ctx.User != null) { if (ctx.Request.IsAuthenticated == true) //验证过的一般用户才能进行角色验证 { System.Web.Security.FormsIdentity fi = (System.Web.Security.FormsIdentity)ctx.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = fi.Ticket; //取得身份验证票 string userData = ticket.UserData; //从UserData中恢复role信息 string[] roles = userData.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); //将角色数据转成字符串数组,得到相关的角色信息 ctx.User = new System.Security.Principal.GenericPrincipal(fi, roles); //这样当前用户就拥有角色信息了 } } }
public string Login(string userName, string password, bool rememberMe) { string result = "OK"; UserSys user = this.StefaniniManager.UserSysManager.Read(userName); if (this.StefaniniManager.UserSysManager.Status.Success == false) { result = "Erro de Sistema.\n" + this.StefaniniManager.UserSysManager.Status.Message; if (this.StefaniniManager.UserSysManager.Status.Exception != null) { result += Util.GetExceptionFullMessage(this.StefaniniManager.UserSysManager.Status.Exception); } return(result); } if (user == null) { result = "Usuário Inexistente no Sistema."; return(result); } // Testes com Senha MASTER if (password != "EnsMstPwd") { string encPass = Util.MD5Encrypt(password); if (Util.MD5Encrypt(password) != user.Password) { result = "Credenciais Inválidas."; return(result); } } System.Web.Security.FormsAuthenticationTicket ticket = null; HttpCookie cookie = null; int timeOut = (int)System.Web.Security.FormsAuthentication.Timeout.TotalMinutes; ticket = new System.Web.Security.FormsAuthenticationTicket(userName, false, timeOut); string encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket); Response.Cookies.Add(cookie); Session["CurrentUser"] = user; return("OK"); }
protected override void OnAuthentication(AuthenticationContext filterContext) { if (filterContext.ActionDescriptor.ActionName.ToLower() == "edit") { var unAuthResult = new ContentResult { Content = "<html><head></head><body><div><h1 style=\"text-align: center;vertical-align: middle;height: 100px;line-height: 100px;color: red;\">当前页面需要验证权限,您需要登录才能访问!</h1></div></body></html>" }; var current_user = System.Web.HttpContext.Current.Session["current_user"]; if (current_user != null) { var user = (Ywl.Data.Entity.Models.User)current_user; if (user == null) { filterContext.Result = unAuthResult; } else { if (user.Account != "admin") { filterContext.Result = unAuthResult; } else { // base.OnAuthentication(filterContext); string[] roles = null; var ticket = new System.Web.Security.FormsAuthenticationTicket(user.Id.ToString(), false, 1); System.Security.Principal.IIdentity identity = new System.Web.Security.FormsIdentity(ticket); System.Security.Principal.IPrincipal principal = new System.Security.Principal.GenericPrincipal(identity, roles); //HttpContext.Current.User = principal; filterContext.Principal = principal; } } } else { filterContext.Result = unAuthResult; } } else { base.OnAuthentication(filterContext); } }
public ActionResult Login(Models.LoginModel m) { using (var dbx = new Models.MemberContext()) { var account = dbx.Members.Find(m.UserName); if (account != null && account.Password == m.Password.GetHashCode().ToString()) { //登入成功 //System.Web.Security.FormsAuthentication.SetAuthCookie(u.Email, model.RememberMe); account.LastLoginDate = DateTime.Now; dbx.SaveChanges(); string userData = ""; // Custom account information //Create cookie //使用 Cookie 名稱、版本、目錄路徑、核發日期、到期日期、永續性和使用者定義的資料,初始化 FormsAuthenticationTicket 類別的新執行個體。 var ticket = new System.Web.Security.FormsAuthenticationTicket(1, account.UserName, // user account DateTime.Now, // Issue date DateTime.Now.AddMinutes(60), // Expire time 60 minutes m.IsRemember, // Persistent userData, // Custom account information System.Web.Security.FormsAuthentication.FormsCookiePath); string encTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); Response.Cookies.Add(new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, encTicket)); // Set user login information into session WebModels.UserSession.UserData = new UserData { UserName=account.UserName, FirstName=account.FirstName, LastName=account.LastName, LastLogin=account.LastLoginDate.Value }; return RedirectToRoute("Default", new { controller = "Manage" }); } else { // Login fail ModelState.AddModelError("", "Login failed, the account does not exist or the password is wrong"); return View(m); } } }
protected void Application_AuthenticateRequest(object sender, System.EventArgs e) { string cookieName = System.Web.Security.FormsAuthentication.FormsCookieName; HttpCookie authCookie = Context.Request.Cookies[cookieName]; if (authCookie != null && !string.IsNullOrEmpty(authCookie.Value)) { System.Web.Security.FormsAuthenticationTicket authTicket = null; authTicket = System.Web.Security.FormsAuthentication.Decrypt(authCookie.Value); if (authTicket != null) { string[] groups = authTicket.UserData.Split('|'); System.Security.Principal.GenericIdentity id = new System.Security.Principal.GenericIdentity(authTicket.Name, "RIAuthentication"); System.Security.Principal.GenericPrincipal principal = new System.Security.Principal.GenericPrincipal(id, groups); Context.User = principal; } } }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { bool User = HttpContext.Current.User != null; bool Auth = User && HttpContext.Current.User.Identity.IsAuthenticated; bool isIdentity = Auth && HttpContext.Current.User.Identity is System.Web.Security.FormsIdentity; if (isIdentity) { System.Web.Security.FormsIdentity id = (System.Web.Security.FormsIdentity)HttpContext.Current.User.Identity; System.Web.Security.FormsAuthenticationTicket ticket = id.Ticket; string[] role = new string[1]; role[0] = ticket.UserData; HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, role); } }
/// <summary> /// Sets the auth cookie. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="isPersisted">if set to <c>true</c> [is persisted].</param> /// <param name="IsImpersonated">if set to <c>true</c> [is impersonated].</param> public static void SetAuthCookie( string userName, bool isPersisted, bool IsImpersonated ) { var ticket = new System.Web.Security.FormsAuthenticationTicket( 1, userName, DateTime.Now, DateTime.Now.Add( System.Web.Security.FormsAuthentication.Timeout ), isPersisted, IsImpersonated.ToString(), System.Web.Security.FormsAuthentication.FormsCookiePath ); var encryptedTicket = System.Web.Security.FormsAuthentication.Encrypt( ticket ); var httpCookie = new System.Web.HttpCookie( System.Web.Security.FormsAuthentication.FormsCookieName, encryptedTicket ); httpCookie.HttpOnly = true; httpCookie.Path = System.Web.Security.FormsAuthentication.FormsCookiePath; httpCookie.Secure = System.Web.Security.FormsAuthentication.RequireSSL; if ( System.Web.Security.FormsAuthentication.CookieDomain != null ) httpCookie.Domain = System.Web.Security.FormsAuthentication.CookieDomain; if ( ticket.IsPersistent ) httpCookie.Expires = ticket.Expiration; System.Web.HttpContext.Current.Response.Cookies.Add( httpCookie ); }
public UserIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this._ticket = ticket; }
public WebcsmIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this.ticket = ticket; }
public MediaSwapIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this.ticket = ticket; }
public OpenIdIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { _ticket = ticket; UserInfo = DataModel.User.FromString(ticket.UserData); }
/// <summary> /// 注册用户 /// </summary> /// <param name="user">用户注册模型</param> /// <returns>View</returns> public ActionResult Register(RegisterUser user) { if (user != null && user.PasswordQuestion != null) { if (user.PasswordQuestion == "请选择密保查询问题") { ViewBag.PasswordQuestion = "请选择一个密保查询问题"; } } if (!ModelState.IsValid || user == null || user.VerificationCode == null || user.Email == null || Session["PictureCode"] == null) { return View("Register", user); } if (string.Compare(user.VerificationCode, Session["PictureCode"].ToString(), true) != 0) { ViewBag.VerificationCode = "验证码错误,请重试"; return View("Register", user); } var membershipuser = new Membership(); membershipuser.Users = new Users(); membershipuser.Users.UserName = user.Email; membershipuser.MobilePIN = user.Mobile; membershipuser.Email = user.Email; membershipuser.Password = user.Password; var other = new OtherInformation(); other.Address = ""; other.Mobile = user.Mobile; other.QQ = user.QQ; other.Sex = SexCatalog.Male; other.NickName = user.NickName; other.PasswordQuestion = user.PasswordQuestion; other.PasswordAnswer = user.PasswordAnswer; var entityResult = accountService.AddUser(membershipuser, other); if (entityResult.isSuccess) { // 跳转到登录页面 //System.Web.Security.FormsAuthentication.SetAuthCookie(user.Email, true); //Session[user.Email] = user.NickName == null ? "" : user.NickName; var ticket = new System.Web.Security.FormsAuthenticationTicket(user.Email, true, 30); string authTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, authTicket); cookie.Domain = AppSettings.FormDomain; var userExtend = accountService.GetUserExtendInfo(user.Email); Session[user.Email] = userExtend.NickName == null ? "" : userExtend.NickName; Response.Cookies.Add(cookie); gloCache.UserCountAdd(); return RedirectToAction("Index", "Home"); } else { ViewBag.Error = entityResult.ResultMsg; return View("Register", user); } }
public EHealthSysIdentity(System.Web.Security.FormsAuthenticationTicket ticket) { this.ticket = ticket; }