protected void Login_Click(object sender, EventArgs e) { if (Page.IsValid) { try { if (Session["CheckRefresh"] != null) { if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString()) { Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); if (Session["rno"] == null) { Utilities.MessageBox_UpdatePanel(UpdatePanel2, "Page has expired!!! Please open this page in a new window.."); } else { bool cptch_expired = false; try { Captcha1.ValidateCaptcha(txt_captcha.Text.Trim()); } catch { cptch_expired = true; } txt_captcha.Text = ""; if (!cptch_expired) { if (Captcha1.UserValidated) { Captcha1.DataBind(); if (!check_user()) { Utilities.MessageBoxShow("Invaild User Id and Password.."); fn_logintrail(false); } else { if (ChkContent.Checked == true) { Response.Cookies["useridd"].Value = txt_login.Text.Trim(); Response.Cookies["pwd"].Value = Password.Text.Trim(); Response.Cookies["useridd"].Expires = DateTime.Now.AddDays(365); Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(365); } else { Response.Cookies["useridd"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["pwd"].Expires = DateTime.Now.AddDays(-1); } fn_logintrail(true); FormsAuthentication.Initialize(); String strRole = role_id; FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, txt_login.Text, DateTime.Now, DateTime.Now.AddMinutes(30), false, strRole, FormsAuthentication.FormsCookiePath); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt))); if (Session["Default_page"] != null) { string str = Session["Default_page"].ToString(); string newstr = str.Replace(".aspx", ""); // Response.Redirect(Session["Default_page"].ToString(), false); Response.Redirect(newstr, false); } else { // Response.Redirect("User/DashBoard.aspx", false); } } } else { Utilities.MessageBox_UpdatePanel(UpdatePanel2, "Invalid Captcha!!! Please enter same characters as you see in image."); } } else { Utilities.MessageBox_UpdatePanel(UpdatePanel2, "Captcha Expired!!! Please re open this page in new window."); } } } else { Utilities.MessageBox_UpdatePanel(UpdatePanel2, "Page Refresh or Back button is now allowed"); } } else { Utilities.MessageBox_UpdatePanel(UpdatePanel2, "Page expired!!! Please re open this page in new window."); } } catch (NullReferenceException) { // Utilities.MessageBox_UpdatePanel_Redirect(UpdatePanel2, "Your Session Has Expired Please Login Again", "../Logout.aspx"); Response.Redirect("login.aspx"); } } }
protected void SucessFullLogin(UserInfo user) { RoleController role = new RoleController(); Session[SessionKeys.LoginHitCount] = null; string userRoles = role.GetRoleNames(user.UserName, GetPortalID); strRoles += userRoles; if (strRoles.Length > 0) { SetUserRoles(strRoles); //SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker]; //sessionTracker.PortalID = GetPortalID.ToString(); //sessionTracker.Username = UserName.Text; //Session[SessionKeys.Tracker] = sessionTracker; SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog(); SLog.SessionTrackerUpdateUsername(UserName.Text, GetPortalID.ToString()); StringBuilder redirectURL = new StringBuilder(); SecurityPolicy objSecurity = new SecurityPolicy(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, GetPortalID.ToString(), FormsAuthentication.FormsCookiePath); // Encrypt the ticket. string encTicket = FormsAuthentication.Encrypt(ticket); //generate random cookieValue string randomCookieValue = GenerateRandomCookieValue(); Session[SessionKeys.RandomCookieValue] = randomCookieValue; //create new cookie with random cookie name and encrypted ticket HttpCookie cookie = new HttpCookie(objSecurity.FormsCookieName(GetPortalID), encTicket); //get default time from setting SageFrameConfig objConfig = new SageFrameConfig(); string ServerCookieExpiration = objConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.ServerCookieExpiration); int expiryTime = Math.Abs(int.Parse(ServerCookieExpiration)); expiryTime = expiryTime < 5 ? 5 : expiryTime; //set cookie expiry time cookie.Expires = DateTime.Now.AddMinutes(expiryTime); //add cookie to the browser Response.Cookies.Add(cookie); if (Request.QueryString["ReturnUrl"] != null) { string PageNotFoundPage = PortalAPI.PageNotFoundURLWithRoot; string UserRegistrationPage = PortalAPI.RegistrationURLWithRoot; string PasswordRecoveryPage = PortalAPI.PasswordRecoveryURLWithRoot; string ForgotPasswordPage = PortalAPI.ForgotPasswordURL; string PageNotAccessiblePage = PortalAPI.PageNotAccessibleURLWithRoot; string ReturnUrlPage = Request.QueryString["ReturnUrl"].Replace("%2f", "-").ToString(); bool IsWellFormedReturnUrlPage = Uri.IsWellFormedUriString(ReturnUrlPage, UriKind.Absolute); string RequestURL = Request.Url.ToString(); Uri RequestURLPageUri = new Uri(RequestURL); string portalHostURL = RequestURLPageUri.AbsolutePath.TrimStart('/'); if (IsWellFormedReturnUrlPage) { Uri ReturnUrlPageUri = new Uri(ReturnUrlPage); string ReturnURl = ReturnUrlPageUri.Scheme + Uri.SchemeDelimiter + ReturnUrlPageUri.Host + ":" + ReturnUrlPageUri.Port; string HostUrl = GetHostURL(); Uri uriHostURL = new Uri(HostUrl); Uri uriReturnURL = new Uri(ReturnURl); var resultCompareURL = Uri.Compare(uriHostURL, uriReturnURL, UriComponents.Host | UriComponents.PathAndQuery, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase); int resultComparePortalURL = 0; if (portalHostURL.ToLower().Contains("portal") && resultCompareURL == 0) { Uri ReturnUrlPageHostUri = new Uri(ReturnUrlPage); string portalReturnURL = ReturnUrlPageHostUri.AbsolutePath.TrimStart('/'); string[] portalReturnURLSplit = portalReturnURL.Split('/'); string ReturnURLSplitPortal = portalReturnURLSplit[0]; string ReturnURLSplitPortalName = portalReturnURLSplit[1]; string ReturnURLWithPortal = ReturnURLSplitPortal + "/" + ReturnURLSplitPortalName; string[] portalHostURLSplit = portalHostURL.Split('/'); string HostURLSplitPortal = portalHostURLSplit[0]; string HostURLSplitPortalName = portalHostURLSplit[1]; string HostURLWithPortal = HostURLSplitPortal + "/" + HostURLSplitPortalName; resultComparePortalURL = string.Compare(ReturnURLWithPortal, HostURLWithPortal); } if (resultCompareURL != 0 || resultComparePortalURL != 0) { PageNotFoundURL(); } } else { PageNotFoundURL(); } if (ReturnUrlPage == PageNotFoundPage || ReturnUrlPage == UserRegistrationPage || ReturnUrlPage == PasswordRecoveryPage || ReturnUrlPage == ForgotPasswordPage || ReturnUrlPage == PageNotAccessiblePage) { redirectURL.Append(GetParentURL); redirectURL.Append(PortalAPI.DefaultPageWithExtension); } else { redirectURL.Append(ResolveUrl(Request.QueryString["ReturnUrl"].ToString())); } } else { if (!IsParent) { redirectURL.Append(GetParentURL); redirectURL.Append("/portal/"); redirectURL.Append(GetPortalSEOName); redirectURL.Append("/"); redirectURL.Append(PortalAPI.DefaultPageWithExtension); } else { redirectURL.Append(GetParentURL); redirectURL.Append("/"); redirectURL.Append(PortalAPI.DefaultPageWithExtension); } } HttpContext.Current.Session[SessionKeys.IsLoginClick] = true; if (Session[SessionKeys.LoginHitCount] != null) { HttpContext.Current.Session.Remove(SessionKeys.LoginHitCount); } Response.Redirect(redirectURL.ToString(), false); } else { FailureText.Text = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "Youarenotauthenticatedtothisportal"));//"You are not authenticated to this portal!"; } }
private bool _existeRolUsuario() { bool blnUsuarioValido = false; try { WSSeguridad.dtstUsuario dsUsuario = new WSSeguridad.dtstUsuario(); string numIdentificacionUsr = this._getNumeroIdentificacion(); if (!string.IsNullOrEmpty(numIdentificacionUsr)) { string periodoVigente = this._getPeriodoVigente(); SitioWebOasis.ProxySeguro.Seguridad seg = new ProxySeguro.Seguridad(); // GESTIONA EL ROL DE UN USUARIO REGISTRADO blnUsuarioValido = seg.AutenticarUsuario(numIdentificacionUsr, "e", periodoVigente, out dsUsuario); // Verificar si el usuario es válido if (blnUsuarioValido) { // Add objeto seguridad a la cache del usuario this._addObjetoSeguridad(); // registrar datos del usuario en la sesión para futuras referencias Usuario usr = this.RegistrarUsuarioEnSesion(dsUsuario); // crear un ticket de autenticación FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, usr.Login, DateTime.Now, DateTime.Now.AddMinutes(20), false, usr.RolActual.ID.ToString()); // Encriptar el ticket string encTicket = FormsAuthentication.Encrypt(ticket); // Crear una cookie y añadir el ticket encriptado como datos HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); // Añadir la cookie a la respuesta Response.Cookies.Add(cookie); // Seteo el tiempo de session en "20" minutos Session.Timeout = 20; } else { this.Session["UsuarioActual"] = new Usuario(); } } }catch (Exception ex) { blnUsuarioValido = false; Errores err = new Errores(); err.SetError(ex, "_existeRolUsuario"); } return(blnUsuarioValido); }
/// <summary> /// Creates the forms authentication ticket /// </summary> /// <param name="customerID">The customer ID</param> /// <returns>Whether or not the ticket was created successfully.</returns> public bool CreateFormsAuthenticationTicket(int customerID) { var command = new SqlHelper(); var row = command.GetRow(@" SELECT c.CustomerID, c.FirstName, c.LastName, c.Company, c.MainCountry, c.EnrollerID, c.SponsorID, c.LanguageID, c.CustomerTypeID, c.CustomerStatusID, c.DefaultWarehouseID, c.CurrencyCode, c.CreatedDate FROM Customers c WHERE c.CustomerID = {0} ", customerID); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, customerID.ToString(), DateTime.Now, DateTime.Now.AddMinutes(GlobalSettings.Backoffice.SessionTimeoutInMinutes), false, string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}", customerID, row["FirstName"].ToString(), row["LastName"].ToString(), row["Company"].ToString(), row["MainCountry"].ToString(), (!Convert.IsDBNull(row["EnrollerID"])) ? Convert.ToInt32(row["EnrollerID"]) : 0, (!Convert.IsDBNull(row["SponsorID"])) ? Convert.ToInt32(row["SponsorID"]) : 0, Convert.ToInt32(row["LanguageID"]), Convert.ToInt32(row["CustomerTypeID"]), Convert.ToInt32(row["CustomerStatusID"]), Convert.ToInt32(row["DefaultWarehouseID"]), "", row["CurrencyCode"].ToString(), Convert.ToDateTime(row["CreatedDate"]).ToShortDateString())); // encrypt the ticket string encTicket = FormsAuthentication.Encrypt(ticket); // create the cookie. HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; //saved user if (cookie == null) { HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); } else { cookie.Value = encTicket; HttpContext.Current.Response.Cookies.Set(cookie); } return(true); }
//[ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string byotp, string bypassword) { if (ModelState.IsValid) { try { var localusermobile = model.MobileLogin.Trim(); if (localusermobile.All(char.IsDigit)) { if (localusermobile.Length == 10) { var userdetail = _mainobj.GetByMobile(localusermobile); if (userdetail == null) { ModelState.AddModelError("MobileLogin", "Mobile is not registered with us, please contact us to get registerd."); return(View()); } else { if (userdetail.userblocked) { ModelState.AddModelError("MobileLogin", "Your account is blocked by admin."); return(View()); } var currentwebsite = "Brick Kiln,"; var userforcuurentwebsite = userdetail.formodule.Contains(currentwebsite); if (!userforcuurentwebsite) { ModelState.AddModelError("MobileLogin", "Mobile is not registered with us for current website, please contact us to get registerd."); return(View()); } } if (!string.IsNullOrEmpty(byotp)) { HelpingMethods hm = new HelpingMethods(); Session["otp"] = hm.RandomNumber(); //Session["otp"] = 1111;/////////////////////////////////////// temp Session["mobilenumber"] = model.MobileLogin; ViewBag.mobilenumber = model.MobileLogin; string message = "OTP is " + Session["otp"].ToString() + " for login to brick kiln support."; var result = hm.sendsmsany(message, ViewBag.mobilenumber); Session["modelvalues"] = model; opttrycount = 0; return(View("ConfirmOTP")); } else if (!string.IsNullOrEmpty(bypassword)) { var upassword = StaticData.GetSHA512(model.Password); var loginresult = _mainobj.GetByMobilePassword(localusermobile, upassword); if (loginresult != null) { FormsAuthentication.Initialize(); HttpContext currentContext = System.Web.HttpContext.Current; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, loginresult.clientname, DateTime.Now, DateTime.Now.AddMinutes(30), true, loginresult.userrole, FormsAuthentication.FormsCookiePath); string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); currentContext.Response.Cookies.Add(cookie); AuthenticateThisRequest(); if (User.IsInRole("Admin")) { return(RedirectToAction("Index", "Description")); } else if (User.IsInRole("Support")) { return(RedirectToAction("ClientDetail", "Support")); } else if (User.IsInRole("Client")) { return(RedirectToAction("Index", "Support")); } } else { ModelState.AddModelError("MobileLogin", "Mobile or Password is not valid"); return(View("LoginAdmin")); } } } } } catch { } } ModelState.AddModelError("MobileLogin", "Mobile is not valid"); return(View()); }
public ActionResult Login(LoginModel login) { if (string.IsNullOrEmpty(login.Account)) { return(Json(new { r = false, m = "用户名不能为空" }, JsonRequestBehavior.AllowGet)); } if (string.IsNullOrEmpty(login.Password)) { return(Json(new { r = false, m = "密码不能为空" }, JsonRequestBehavior.AllowGet)); } var loginuser = unitOfWork.DUserInfo.Get(p => p.UserName == login.Account).FirstOrDefault(); if (loginuser != null) { DateTime expiration = DateTime.Now.AddDays(7); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(loginuser.ID.ToString(), true, 30000); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); Response.Cookies.Set(cookie); return(Json(new { r = true }, JsonRequestBehavior.AllowGet)); } else { return(Json(new { r = false, m = "用户名或者密码错误" }, JsonRequestBehavior.AllowGet)); } }
//[ValidateAntiForgeryToken] public ActionResult IniciarSesion(AutenticacionViewModel inicioSesionModel) { if (ModelState.IsValid) { string nombreCompleto = String.Empty; string nombrePerfil = String.Empty; long usuarioId = 0; string NombreUsuario = ""; string Contrasena = ""; string controlador = "ConsultaPersona"; string accion = "ConsultaPersona"; int usuarioInterno = 0; Usuario registro = new Usuario(); NombreUsuario = inicioSesionModel.NombreUsuario; Contrasena = inicioSesionModel.Contrasena; registro = usuSrv.UsuarioConsultarPorUsuarioYContrsena(NombreUsuario, Contrasena); if (registro != null && registro.tipoMensaje == 3) { ModelState.AddModelError("", registro.mensajeNotificacion); } if (registro != null) { nombreCompleto = registro.NOMBRES_USUARIO + " " + registro.APELLIDOS_USUARIO; usuarioId = registro.ID_USUARIO; } else {//Usuario incorrecto String mensaje = "Usuario y/o contraseña invalida"; ModelState.AddModelError("", mensaje); return(View(new AutenticacionViewModel())); } Session["UsuarioId"] = usuarioId; Session["NombreCompleto"] = nombreCompleto; var authTicket = new FormsAuthenticationTicket(1, nombreCompleto, DateTime.Now, DateTime.Now.AddMinutes(30), true, usuarioId.ToString() + "|" + inicioSesionModel.NombreUsuario + "|" + nombrePerfil + "|" + usuarioInterno.ToString()); string cookieContents = FormsAuthentication.Encrypt(authTicket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents) { Expires = authTicket.Expiration, Path = FormsAuthentication.FormsCookiePath, Secure = false, HttpOnly = true }; Response.Cookies.Add(cookie); if (inicioSesionModel.Recordarme) { HttpCookie httpCookie = new HttpCookie("DatosRecordarmeSarlaft"); httpCookie["NombreUsuario"] = inicioSesionModel.NombreUsuario; httpCookie.Expires = DateTime.Now.AddDays(30d); httpCookie.HttpOnly = true; Response.Cookies.Add(httpCookie); } else { if (Request.Cookies["DatosRecordarmeSarlaft"] != null) { HttpCookie httpCookie = new HttpCookie("DatosRecordarmeSarlaft") { Expires = DateTime.Now.AddDays(-1d) }; Response.Cookies.Add(httpCookie); } } return(RedirectToActionPermanent(accion, controlador)); } return(View(inicioSesionModel)); }
public async Task <ActionResult> btn_login(string username, string password, string capcha, bool remember) { string strreturn = ""; var value = "false"; var check_role = false; if (Session["randomStr"] != null) { string getSession = Session["randomStr"].ToString(); var list_role = Roles.GetRolesForUser(username); if (list_role.Length > 0) { for (var i = 0; i < list_role.Length; i++) { if (list_role[i] != "" && list_role[i] != "engineer") { check_role = true; } } } if (check_role) { if (Membership.ValidateUser(username, password) && capcha == getSession) { var dnow = DateTime.Now.AddDays(1); string formsAuthSalt = Membership.GeneratePassword(20, 2); // string userData = string.Join("|", GetCustomUserRoles()); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // ticket version username, // authenticated username DateTime.Now, // issueDate new DateTime(dnow.Year, dnow.Month, dnow.Day, 0, 5, 0), // expiryDate true, // true to persist across browser sessions formsAuthSalt, // can be used to store additional user data FormsAuthentication.FormsCookiePath); // the path for the cookie // Encrypt the ticket using the machine key string encryptedTicket = FormsAuthentication.Encrypt(ticket); // Add the cookie to the request to save it HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.Expires = remember ? DateTime.Now.AddDays(30) : DateTime.Now.AddDays(1); cookie.HttpOnly = true; cookie.Secure = true; Response.Cookies.Add(cookie); // Your redirect logic // Response.Redirect(FormsAuthentication.GetRedirectUrl(username, chkremember.Checked)); MembershipUser user = Membership.GetUser(username); user.Comment = formsAuthSalt; Membership.UpdateUser(user); value = "true"; // login child site if (Roles.IsUserInRole(username, "admin") || Roles.IsUserInRole(username, "admin_installer")) { var std = new StandardController(); var model = new { data = std.GetBodyLogin(username, password, remember) }; //string apiUrl = ConfigurationManager.AppSettings["Child_URL"] + "member/login"; string url = ConfigurationManager.AppSettings["Child_URL"] + "member/login?token=" + std.GetBodyLogin(username, password, remember); strreturn = "{ \"status\" : \"1\" , \"autourl\" : \"" + url + "\"}"; // Response.Redirect(apiUrl); // HttpClient client = new HttpClient(); //client.BaseAddress = new Uri(apiUrl); //client.DefaultRequestHeaders.Accept.Clear(); //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); ////var json = JsonConvert.SerializeObject(model); ////var json_body = new StringContent(json, Encoding.UTF8, "application/json"); ////HttpResponseMessage response = await client.PostAsync(apiUrl, json_body); //HttpResponseMessage response = await client.GetAsync(apiUrl); //string responseContent = await response.Content.ReadAsStringAsync(); } else { strreturn = "{ \"status\" : \"3\" , \"autourl\" : \"" + "" + "\"}"; } } } else { strreturn = "{ \"status\" : \"2\" , \"autourl\" : \"" + "" + "\"}"; //value = "engineer"; } } else { // value = "false"; strreturn = "{ \"status\" : \"0\" , \"autourl\" : \"" + "" + "\"}"; } // return value; return(Content(strreturn, "application/json")); }
public async Task <ActionResult> Login(LoginViewModel model, string returnUrl) { //Check to make sure form is valid. if (!ModelState.IsValid) { return(View(model)); } #region GetUserId // This entire section is meant to get the UserID. This is done either with the legend or new SHA1 hashing. //This is for deprecated SHA1 Hash done on SQL Server //Need to get the userID in order to get the User object. There are two ways. The Deprecated way //uses the Login_SP_Result stored procedure to send SQL Server model.password, SHA1Hash it there //and then compare it to what the data base has. UserForAuth, stores the SHA1Hash directly on the DB. //So C# handles model.password SHA1Hashing and then compares it to whats on the DB. int userid = 0; //Check to see if it's an old password. Login_SP_Result legendUserForAuth = context.Login_SP(model.UserName, model.Password).FirstOrDefault(); if (legendUserForAuth != null) { //LegendUser exits and the ID can be queried directly. userid = legendUserForAuth.ID; } //It's either an new SHA1 Hash or its just not a valid username. else { //Checks to see if UserName Exists var newUserForAuth = db.Users.Where(s => s.UserName == model.UserName).FirstOrDefault(); if (newUserForAuth != null) { //UserName exists if (Hash(model.Password) == newUserForAuth.Password) { //Passwords match userid = newUserForAuth.ID; } else { HttpCookie cookie = new HttpCookie("Cookie1", ""); cookie.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie); //Passwords don't match TODO: Change to "Invalid Login Attempt" ModelState.AddModelError("", "Invalid Password Attempt."); return(View(model)); } } else { HttpCookie cookie = new HttpCookie("Cookie1", ""); cookie.Expires = DateTime.Now.AddYears(-1); Response.Cookies.Add(cookie); //UserName Straight up doesn't exist. TODO: Change to "Invalid Login Attempt" ModelState.AddModelError("", "Invalid User Name."); return(View(model)); } } #endregion #region AuthenticateUser User user = await db.Users.FindAsync(userid); //User mustchange password, ie it equals Chang3m3 if (user.MustChange == true) { return(RedirectToAction("ChangePassword", "Account", new { area = "Identity" })); } var licenseclaim = db.Licenses.Where(s => s.UserID == userid).FirstOrDefault(); var ClientID = licenseclaim.ClientID; var client = db.Clients.Where(s => s.ID == ClientID).FirstOrDefault(); long clientNumber = client.ClientNumber.Value; string clientName = client.Name; var userRightsId = licenseclaim.RightsID; var userRight = db.Rights.Where(s => s.ID == userRightsId).FirstOrDefault(); string userRightName = userRight.Right1; if (getAuthorizedClientList().Contains(clientNumber)) { CustomSerializeModel userModel = new Models.CustomSerializeModel() { UserId = user.ID, UserLicenseRight = clientNumber, RoleName = userRightName, UserName = user.UserName }; string userData = JsonConvert.SerializeObject(userModel); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket ( 1, model.UserName, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData ); string enTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie faCookie = new HttpCookie("Cookie1", enTicket); Response.Cookies.Add(faCookie); Debug.WriteLine(clientName); var relativePath = "../../Areas/" + clientName + "/Views/Home/Index.cshtml"; var absolutePath = HttpContext.Server.MapPath(relativePath); if (System.IO.File.Exists(absolutePath)) { return(RedirectToAction("Index", "Home", new { area = clientName })); } else { LogOut(); ModelState.AddModelError("", "Something went wrong. Please contact customer support."); return(View(model)); } } else { ModelState.AddModelError("", "Invalid."); return(View(model)); } #endregion }
protected void LoginButton_Click(object sender, EventArgs e) { MembershipController member = new MembershipController(); RoleController role = new RoleController(); UserInfo user = member.GetUserDetails(GetPortalID, UserName.Text); if (user.UserExists && user.IsApproved) { if (!(string.IsNullOrEmpty(UserName.Text) && string.IsNullOrEmpty(PasswordAspx.Text))) { if (PasswordHelper.ValidateUser(user.PasswordFormat, PasswordAspx.Text, user.Password, user.PasswordSalt)) { string userRoles = role.GetRoleNames(user.UserName, GetPortalID); strRoles += userRoles; if (strRoles.Length > 0) { SetUserRoles(strRoles); SessionTracker sessionTracker = (SessionTracker)Session[SessionKeys.Tracker]; sessionTracker.PortalID = GetPortalID.ToString(); sessionTracker.Username = UserName.Text; Session[SessionKeys.Tracker] = sessionTracker; SageFrame.Web.SessionLog SLog = new SageFrame.Web.SessionLog(); SLog.SessionTrackerUpdateUsername(sessionTracker, sessionTracker.Username, GetPortalID.ToString()); StringBuilder redirectURL = new StringBuilder(); SecurityPolicy objSecurity = new SecurityPolicy(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, GetPortalID.ToString(), FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); string randomCookieValue = GenerateRandomCookieValue(); Session[SessionKeys.RandomCookieValue] = randomCookieValue; HttpCookie cookie = new HttpCookie(objSecurity.FormsCookieName(GetPortalID), encTicket); SageFrameConfig objConfig = new SageFrameConfig(); string ServerCookieExpiration = objConfig.GetSettingValueByIndividualKey(SageFrameSettingKeys.ServerCookieExpiration); int expiryTime = Math.Abs(int.Parse(ServerCookieExpiration)); expiryTime = expiryTime < 5 ? 5 : expiryTime; cookie.Expires = DateTime.Now.AddMinutes(expiryTime); Response.Cookies.Add(cookie); ServiceSecurity.IssueToken(GetPortalID); if (Request.QueryString["ReturnUrl"] != null) { string PageNotFoundPage = PortalAPI.PageNotFoundURLWithRoot; string UserRegistrationPage = PortalAPI.RegistrationURLWithRoot; string PasswordRecoveryPage = PortalAPI.PasswordRecoveryURLWithRoot; string ForgotPasswordPage = PortalAPI.ForgotPasswordURL; string PageNotAccessiblePage = PortalAPI.PageNotAccessibleURLWithRoot; string ReturnUrlPage = Request.QueryString["ReturnUrl"].Replace("%2f", "-").ToString(); if (ReturnUrlPage == PageNotFoundPage || ReturnUrlPage == UserRegistrationPage || ReturnUrlPage == PasswordRecoveryPage || ReturnUrlPage == ForgotPasswordPage || ReturnUrlPage == PageNotAccessiblePage) { redirectURL.Append(GetParentURL); redirectURL.Append(PortalAPI.DefaultPageWithExtension); } else { redirectURL.Append(ResolveUrl(Request.QueryString["ReturnUrl"].ToString())); } } else { if (!IsParent) { redirectURL.Append(GetParentURL); redirectURL.Append("/portal/"); redirectURL.Append(GetPortalSEOName); redirectURL.Append("/"); redirectURL.Append(ssc.GetStoreSettingsByKey(StoreSetting.SingleCheckOutURL, GetStoreID, GetPortalID, GetCurrentCultureName)); redirectURL.Append(SageFrameSettingKeys.PageExtension); } else { redirectURL.Append(GetParentURL); redirectURL.Append("/"); redirectURL.Append(ssc.GetStoreSettingsByKey(StoreSetting.SingleCheckOutURL, GetStoreID, GetPortalID, GetCurrentCultureName)); redirectURL.Append(SageFrameSettingKeys.PageExtension); } } int customerID = GetCustomerID; if (customerID == 0) { CustomerGeneralInfo sageUserCust = CustomerGeneralInfoController.CustomerIDGetByUsername(user.UserName, GetPortalID, GetStoreID); if (sageUserCust != null) { customerID = sageUserCust.CustomerID; } } UpdateCartAnonymoususertoRegistered(GetStoreID, GetPortalID, customerID, sessionCode); Response.Redirect(redirectURL.ToString(), false); } else { FailureText.Text = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "Youarenotauthenticatedtothisportal")); } } else { FailureText.Text = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "UsernameandPasswordcombinationdoesntmatched"));//"Username and Password combination doesn't matched!"; } } } else { FailureText.Text = string.Format("<p class='sfError'>{0}</p>", GetSageMessage("UserLogin", "UserDoesnotExist")); } }
public ActionResult AutenticarUsuario(UsuarioAutenticarModelView model) { if (ModelState.IsValid) { try { UsuarioRepository rep = new UsuarioRepository(); Usuario u = rep.Find(model.Email, Criptografia.EncriptarSenha(model.Senha)); if (u != null) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(u.Email, false, 10); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); Response.Cookies.Add(cookie); return(RedirectToAction("Index", "Principal", new { area = "AreaRestrita" })); } else { ViewBag.Mensagem = "Acesso negado. Usuário não encontrado."; } } catch (Exception e) { ViewBag.Mensagem = "Ocorreu um erro: " + e.Message; } } return(View("Login")); }
public ActionResult Login(Model_Login model) { if (User.Identity.IsAuthenticated) { return(RedirectToAction("index", "Dashboard")); } if (!ModelState.IsValid) { ViewBag.State = "Error"; return(View("Login", model)); } model.Password = model.Password.PersianToEnglish(); model.Username = model.Username.PersianToEnglish(); var q = db.Tbl_Login.Where(a => a.Login_Email == model.Username || a.Login_Mobile == model.Username).SingleOrDefault(); if (q == null) { TempData["TosterState"] = "error"; TempData["TosterType"] = TosterType.Maseage; TempData["TosterMassage"] = "کاربر یافت نشد !"; return(View()); } var SaltPassword = model.Password + q.Login_PasswordSalt; var SaltPasswordBytes = Encoding.UTF8.GetBytes(SaltPassword); var SaltPasswordHush = Convert.ToBase64String(SHA512.Create().ComputeHash(SaltPasswordBytes)); if (q.Login_PasswordHash == SaltPasswordHush) { string s = string.Empty; s = Rep_UserRole.Get_RoleNameWithID(q.Login_BaseRoleID); var Ticket = new FormsAuthenticationTicket(0, model.Username, DateTime.Now, model.RemenberMe ? DateTime.Now.AddDays(30) : DateTime.Now.AddDays(1), true, s); var EncryptedTicket = FormsAuthentication.Encrypt(Ticket); var Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, EncryptedTicket) { Expires = Ticket.Expiration }; Response.Cookies.Add(Cookie); TempData["TosterState"] = "success"; TempData["TosterType"] = TosterType.Maseage; TempData["TosterMassage"] = "خوش آمدید"; return(RedirectToAction("index", "Dashboard")); } else { TempData["TosterState"] = "error"; TempData["TosterType"] = TosterType.Maseage; TempData["TosterMassage"] = "پسورد نادرست است !"; return(View()); } }
/// <summary> /// All The Methods That are used in coding /// </summary> #region Methods public void login() { Session["EndSubscriptionFlag"] = null; try { if (txtEmail.Text != " " && txtPassword.Text != "") { AuthenticateUser(); us_ID = Convert.ToInt32(Session["UserID"]); if (us_ID > 0) { selectUserRole(); int c_id = Convert.ToInt32(Session["company_id"]); ObjectParameter freeCount = new ObjectParameter("free_count", typeof(int)); ObjectParameter subscriptionCount = new ObjectParameter("Subscription_count", typeof(int)); var r = context.sp_checklicense(c_id, us_ID, freeCount, subscriptionCount); if (Convert.ToInt32(subscriptionCount.Value) > 0) { if (Convert.ToInt32(freeCount.Value) > 0) { string userData = string.Empty; string role = Convert.ToString(Session["Rolename"]); if (role == "Sales Manager") { userData = "Sales"; } else if (role == "Purchase Manager") { userData = "Purchase"; } else if (role == "Manager" || role == "") { userData = "Manager"; } Session["UserRoleSession"] = userData; if (!string.IsNullOrEmpty(userData)) { // create a new ticket used for authentication if (cbRemember.Checked == true) { Response.Cookies["us_ID"].Value = txtEmail.Text; Response.Cookies["enPswd"].Value = txtPassword.Text; Response.Cookies["us_ID"].Expires = DateTime.Now.AddDays(15); Response.Cookies["enPswd"].Expires = DateTime.Now.AddDays(15); } else { Response.Cookies["us_ID"].Expires = DateTime.Now.AddDays(-1); Response.Cookies["enPswd"].Expires = DateTime.Now.AddDays(-1); } FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, txtEmail.Text, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData, FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); if (cbRemember.Checked) { HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.Expires = ticket.Expiration; HttpContext.Current.Response.Cookies.Set(cookie); } else { FormsAuthentication.SetAuthCookie(txtEmail.Text, false); } } string returnUrl = Request.QueryString["ReturnUrl"]; if (role.Equals("Purchase Manager")) { returnUrl = "Purchases/Purchase.aspx"; } else if (role == "Sales Manager") { returnUrl = "Sales/Sale.aspx"; } else if (role == "Manager" || role == "") { returnUrl = "Home.aspx"; } Response.Redirect(@"~/" + returnUrl, false); } else { ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('Your free count has over.');", true); Session["CustomerId"] = txtEmail.Text; } } else { ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('Your subscription has been ended, Please Choose any Of Our Plan To Continue.');", true); Session["CustomerId"] = txtEmail.Text; } } else { ClientScript.RegisterStartupScript(this.GetType(), "Pop", "openalert('User Name Or Password Is Invalid');", true); } } else { lblError.Visible = true; lblError.Text = "Please Enter Your Email ID and Password"; } } catch (Exception ex) { ErrorLog.saveerror(ex); } }
public HttpResponseMessage DoLogin(string username, string password) { LoginModel loginModel = new LoginModel(); try { string user = username.Trim().ToUpper(); string pw = password.Trim(); MyPrincipal upro = null; bool found = false; MyIdentity identity = null; if ((HttpContext.Current.Cache[user] != null)) { upro = (MyPrincipal)HttpContext.Current.Cache.Get(user); identity = (MyIdentity)upro.Identity; HttpContext.Current.User = upro; found = true; } if (!found) { try { upro = MySecurityProvider.BuildNewIdentity(user, "", pw, "Form").Result; } catch (System.Exception ex) { ErrorLogInfo error = new ErrorLogInfo(); error.freeTextDetails = ex.Message; error.logCode = "ERR111"; error.loggingAppCode = "SCA"; error.loggingTime = System.DateTime.Now; error.uniqueLogID = System.DateTime.Now.Ticks.ToString(); _log.Error(error); loginModel.Error = ex.Message; loginModel.success = "false"; return(this.Request.CreateResponse <LoginModel>(HttpStatusCode.InternalServerError, loginModel)); } } //se l'utente ha fornito username e password corretta if (upro != null && (((MyIdentity)upro.Identity).checkIdentity(user, pw))) { //se l'utente non era in cache carico il profilo utente if (!found) { //upro = MySecurityProvider.BuildPrincipal(identity, "0"); HttpContext.Current.Cache.Add(user, upro, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(CACHEEXPIRATION), System.Web.Caching.CacheItemPriority.AboveNormal, null); } //a questo punto ho riunito le due strade //controllo se l'utente è già loggato //if (upro.isLoggedIn) errorlabel.Text = "Accesso impossibile.<br /><br /><b>ATTENZIONE: Account già in uso!!</b>"; if (false) { } else { MailLogInfo logInfo = new MailLogInfo(); logInfo.logCode = "LON"; logInfo.loggingAppCode = "MAIL"; logInfo.loggingTime = System.DateTime.Now; logInfo.uniqueLogID = System.DateTime.Now.Ticks.ToString(); logInfo.userID = user; logInfo.freeTextDetails = string.Empty; _log.Info(logInfo); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(user, false, 15); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); HttpContext.Current.Response.Cookies.Add(cookie); //Response.Cookies.Add(cookie); // upro.isLoggedIn = true; HttpContext.Current.User = upro; HttpContext.Current.Cache.Insert(user, upro, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(CACHEEXPIRATION), System.Web.Caching.CacheItemPriority.AboveNormal, null); loginModel.success = "true"; loginModel.ResponseUrl = "pages/Common/Default.aspx"; } } // hanno provato ad inserie uno username giusto ma una password sbagliata(grave) else { loginModel.success = "false"; loginModel.Error = "Attenzione! Credenziali di accesso errate"; return(this.Request.CreateResponse <LoginModel>(HttpStatusCode.BadRequest, loginModel)); } } catch (System.Exception e0) { loginModel.Error = e0.Message; loginModel.success = "false"; return(this.Request.CreateResponse <LoginModel>(HttpStatusCode.InternalServerError, loginModel)); } return(this.Request.CreateResponse <LoginModel>(HttpStatusCode.OK, loginModel)); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string action = context.Request.Params["action"]; try { switch (action) { case "getuser": if (context.Request.IsAuthenticated) { FormsIdentity id = (FormsIdentity)context.User.Identity; FormsAuthenticationTicket tickets = id.Ticket; //反序列化获取票证里的用户对象(这个用户对象是cookie里保存的,不一定是数据库里最新的用户状态) DriveMgr.Model.User userFromCookie = new JavaScriptSerializer().Deserialize <DriveMgr.Model.User>(tickets.UserData); //执行登录操作(获取数据库里最新的用户对象) DriveMgr.Model.User userFromDB = new DriveMgr.BLL.User().UserLogin(userFromCookie.UserId, userFromCookie.UserPwd); if (userFromDB == null) //修改了用户名或密码 { FormsAuthentication.SignOut(); //干掉cookie context.Response.Write("{\"msg\":\"用户名或密码错误!\",\"success\":false}"); } else if (!userFromDB.IsAble) //管理员禁用了这个账户 { FormsAuthentication.SignOut(); //干掉cookie context.Response.Write("{\"msg\":\"用户已被禁用!\",\"success\":false}"); } else if (userFromCookie.IfChangePwd != userFromDB.IfChangePwd || userFromCookie.UserName != userFromDB.UserName) //如果这两个字段修改了需要重新生成cookie { FormsAuthentication.SignOut(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket ( 2, userFromDB.UserId, DateTime.Now, tickets.Expiration, false, new JavaScriptSerializer().Serialize(userFromDB) //序列化新的用户对象 ); string encTicket = FormsAuthentication.Encrypt(ticket); //加密 HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); if (ticket.Expiration != new DateTime(9999, 12, 31)) //不是默认时间才设置过期时间,否则会话cookie { cookie.Expires = tickets.Expiration; } context.Response.Cookies.Add(cookie); //写入cookie //输出新对象 context.Response.Write("{\"msg\":" + new JavaScriptSerializer().Serialize(userFromDB) + ",\"success\":true}"); } else { context.Response.Write("{\"msg\":" + tickets.UserData + ",\"success\":true}"); } } else { context.Response.Write("{\"msg\":\"nocookie\",\"success\":false}"); } break; case "iflogin": //System.Threading.Thread.Sleep(5000); if (context.Request.IsAuthenticated) { FormsIdentity id = (FormsIdentity)context.User.Identity; FormsAuthenticationTicket tickets = id.Ticket; //获取票证里序列化的用户对象(反序列化) DriveMgr.Model.User userCheck = new JavaScriptSerializer().Deserialize <DriveMgr.Model.User>(tickets.UserData); //执行登录操作 DriveMgr.Model.User userReLogin = new DriveMgr.BLL.User().UserLogin(userCheck.UserId, userCheck.UserPwd); if (userReLogin == null) { FormsAuthentication.SignOut(); context.Response.Write("{\"msg\":\"用户名或密码错误!\",\"success\":false}"); } else if (!userReLogin.IsAble) { FormsAuthentication.SignOut(); context.Response.Write("{\"msg\":\"用户已被禁用!\",\"success\":false}"); } else { //记录登录日志 DriveMgr.Model.LoginLog loginInfo = new Model.LoginLog(); loginInfo.UserIp = context.Request.UserHostAddress; loginInfo.City = context.Request.Params["city"] ?? "未知"; //访问者所处城市 loginInfo.UserName = context.User.Identity.Name; loginInfo.Success = true; new DriveMgr.BLL.LoginLog().WriteLoginLog(loginInfo); context.Response.Write("{\"msg\":\"已登录过,正在跳转!\",\"success\":true}"); } } else { context.Response.Write("{\"msg\":\"nocookie\",\"success\":false}"); } break; case "login": //System.Threading.Thread.Sleep(5000); string userIp = context.Request.UserHostAddress; string city = context.Request.Params["city"] ?? "未知"; string remember = context.Request.Params["remember"] ?? ""; //记住密码天数 string name = context.Request.Params["loginName"]; string pwd = DriveMgr.Common.Md5.GetMD5String(context.Request.Params["loginPwd"]); //md5加密 DateTime?lastLoginTime; if (new DriveMgr.BLL.LoginLog().CheckLogin(userIp, out lastLoginTime) != null) { DateTime dtNextLogin = Convert.ToDateTime(lastLoginTime); context.Response.Write("{\"msg\":\"密码错误次数达到5次,请在" + dtNextLogin.AddMinutes(30).ToShortTimeString() + "之后再登陆!\",\"success\":false}"); } else { DriveMgr.Model.LoginLog loginInfo = new Model.LoginLog(); loginInfo.UserName = name; loginInfo.UserIp = userIp; loginInfo.City = city; DriveMgr.Model.User currentUser = new DriveMgr.BLL.User().UserLogin(name, pwd); if (currentUser == null) { context.Response.Write("{\"msg\":\"用户名或密码错误!\",\"success\":false}"); loginInfo.Success = false; new DriveMgr.BLL.LoginLog().WriteLoginLog(loginInfo); } else if (currentUser.IsAble == false) { context.Response.Write("{\"msg\":\"用户已被禁用!\",\"success\":false}"); loginInfo.Success = false; new DriveMgr.BLL.LoginLog().WriteLoginLog(loginInfo); } else { //记录登录日志 loginInfo.Success = true; new DriveMgr.BLL.LoginLog().WriteLoginLog(loginInfo); context.Response.Write("{\"msg\":\"登录成功!\",\"success\":true}"); DateTime dateCookieExpires; //cookie有效期 switch (remember) { case "notremember": dateCookieExpires = new DateTime(9999, 12, 31); //默认时间 break; case "oneday": dateCookieExpires = DateTime.Now.AddDays(1); break; case "sevenday": dateCookieExpires = DateTime.Now.AddDays(7); break; case "onemouth": dateCookieExpires = DateTime.Now.AddDays(30); break; case "oneyear": dateCookieExpires = DateTime.Now.AddDays(365); break; default: dateCookieExpires = new DateTime(9999, 12, 31); break; } FormsAuthenticationTicket ticket = new FormsAuthenticationTicket ( 2, currentUser.UserId, DateTime.Now, dateCookieExpires, false, new JavaScriptSerializer().Serialize(currentUser) //序列化当前用户对象 ); string encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); if (dateCookieExpires != new DateTime(9999, 12, 31)) //不是默认时间才设置过期时间,否则会话cookie { cookie.Expires = dateCookieExpires; } context.Response.Cookies.Add(cookie); } } break; case "logout": FormsAuthentication.SignOut(); context.Response.Write("{\"msg\":\"退出成功!\",\"success\":true}"); break; default: context.Response.Write("{\"msg\":\"参数错误!\",\"success\":false}"); break; } } catch (Exception ex) { context.Response.Write("{\"msg\":\"" + DriveMgr.Common.JsonHelper.StringFilter(ex.Message) + "\",\"success\":false}"); } }
public ActionResult Login([Bind(Include = "userName,password")] User user) { //RoleUser roleUser = db.ValidateUser(user.Username, user.Password).FirstOrDefault(); //Validate_User_Result roleUser = db.Validate_User(user.Username, user.Password).FirstOrDefault(); //string hashPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password, "SHA1"); //Validate_User_Result roleUser = db.Validate_User(user.Username, hashPassword).FirstOrDefault(); User userFound = db.Users.Where(x => x.userName == user.userName) .Where(x => x.password == user.password) .FirstOrDefault(); string message = string.Empty; if (userFound == null) { message = "Username and/or password is incorrect."; } else { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.userName, DateTime.Now, DateTime.Now.AddMinutes(2880), false, userFound.typeOfUser, 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(Request.Form["ReturnUrl"])) { return(RedirectToAction(Request.Form["ReturnUrl"].Split('/')[2])); } else { return(RedirectToAction("Index")); } } //switch (roleUser.UserId.Value) //{ // case -1: // message = "Username and/or password is incorrect."; // break; // default: // FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(2880), user.RememberMe, roleUser.Roles, 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(Request.Form["ReturnUrl"])) // { // return RedirectToAction(Request.Form["ReturnUrl"].Split('/')[2]); // } // else // { // return RedirectToAction("Index"); // } //} ViewBag.Message = message; return(View(user)); }
protected void btnLogin_Click(object sender, EventArgs e) { // Initialize FormsAuthentication, for what it's worth FormsAuthentication.Initialize(); // Create our connection and command objects SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLDebugConnectionString"].ToString()); SqlCommand cmd = new SqlCommand("USER_LOGIN", conn); // Fill our parameters cmd.Parameters.Add("@userName", SqlDbType.NVarChar, 64).Value = Username.Value; cmd.Parameters.Add("@password", SqlDbType.NVarChar, 128).Value = FormsAuthentication.HashPasswordForStoringInConfigFile(Password.Value, "SHA1"); // Or "sha1" cmd.CommandType = CommandType.StoredProcedure; // Execute the command conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { // Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version Username.Value, // Username associated with ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire true, // "true" for a persistent user cookie reader.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 cookie = 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) { cookie.Expires = ticket.Expiration; } // Add the cookie to the list for outgoing response Response.Cookies.Add(cookie); VerifyUserRole(); } else { // Never tell the user if just the username is password is incorrect. // That just gives them a place to start, once they've found one or // the other is correct! ErrorLabel.Text = "Username / password incorrect. Please try again."; ErrorLabel.Visible = true; // Redirect to requested URL, or homepage if no previous page // requested string returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl == null) { returnUrl = "/"; } // Don't call FormsAuthentication.RedirectFromLoginPage since it // could // replace the authentication ticket (cookie) we just added Response.Redirect(returnUrl); } reader.Close(); conn.Close(); }
public ActionResult DoLogin(LoginModel model) { Organization org = this.tdb.Organizations.Single(y => y.Id == model.OrganizationId); // Run the re-captcha checks unless we allow re-captcha to be bypassed or the client has not specified debug mode if (!AppSettings.RecaptchaAllowBypass || !this.Request.Params.ToString().Split('&').Contains("debug")) { if (!ModelState.IsValid) { LoginModel newModel = GetLoginModel(model, App_GlobalResources.TrifoliaLang.RecaptchaInvalid); AuditEntryExtension.SaveAuditEntry("Login", "Failed - The re-captcha response specified is not valid", model.Username, org.Name); return(View("Login", newModel)); } } if (CheckPoint.Instance.ValidateUser(model.Username, org.Name, model.Password)) { Response.Cookies.Clear(); string userData = string.Format("{0}={1}", CheckPoint.AUTH_DATA_ORGANIZATION, org.Name); FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 2, model.Username, DateTime.Now, DateTime.Now.AddDays(20), model.RememberMe, userData); string encAuthTicket = FormsAuthentication.Encrypt(authTicket); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encAuthTicket); if (model.RememberMe) { faCookie.Expires = DateTime.Now.AddDays(20); } Response.Cookies.Set(faCookie); // Audit the login AuditEntryExtension.SaveAuditEntry("Login", "Success", model.Username, org.Name); if (!string.IsNullOrEmpty(model.ReturnUrl)) { return(Redirect(model.ReturnUrl)); } return(RedirectToAction("LoggedInIndex", "Home")); } else { LoginModel newModel = GetLoginModel( model.ReturnUrl, model.Username, model.OrganizationId, App_GlobalResources.TrifoliaLang.AuthenticationInvalid, model.RememberMe); // Audit the failed login AuditEntryExtension.SaveAuditEntry("Login", "Failed", model.Username, org.Name); return(View("Login", newModel)); } }
protected override bool AuthorizeCore(HttpContextBase httpContext) { //本系统验证登陆 if (!HttpContext.Current.User.Identity.IsAuthenticated) { //sso服务端验证是否登陆 AbsAuthorizeLoginResult result = AbsAuthorizeLogin.AuthorizeCore(httpContext.Request["token"], "http://localhost:54805/"); if (!result.Success) { httpContext.Response.StatusCode = 401; return(false); } else { string CookieUser = JsonConvert.SerializeObject(new CookieUser() { UserId = result.User.UserId, RoleId = result.User.UserRole.ID, LoginName = result.User.LoginName, RoleName = result.User.UserRole.Name }); //序列化用户实体 FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, result.User.LoginName, DateTime.Now, DateTime.Now.AddDays(1), false, CookieUser); HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket)); //加密身份信息,保存至Cookie httpContext.Response.Cookies.Add(Cookie); Cookie.HttpOnly = true; return(true); } } return(true); }
//E' presente anche nella Default.aspx //public bool IsMobile() //{ // bool retValue = false; // try //try , because sometimes user agent is empty // { // string ua = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower(); // string[] uaArray = { "android", "maui", "ppc", "opera mobi", "symbian", "series", "nokia", "mot-", "motorola", "lg-", "lge", "nec-", "lg/", "samsung", "sie-", "sec-", "sgh-", "sonyericsson", "sharp", "windows ce", "portalmmm", "o2-", "docomo", "philips", "panasonic", "sagem", "smartphone", "up.browser", "up.link", "googlebot-mobile", "googlebot-image", "slurp", "spring", "alcatel", "sendo", "blackberry", "opera mini", "opera 2", "netfront", "mobilephone mm", "vodafone", "avantgo", "palmsource", "siemens", "toshiba", "i-mobile", "asus", "kwc", "htc", "softbank", "playstation", "nitro", "ipod", "google wireless transcoder", "t-mobile", "obigo", "brew" }; //"ice", // bool foundInArray = false; // foreach (string s in uaArray) // { // if (ua.IndexOf(s) > -1) // { // foundInArray = true; // break; // } // } // if (foundInArray == true || HttpContext.Current.Request.Browser.IsMobileDevice || HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT"].Contains("application/vnd.wap.xhtml+xml")) // retValue = true; // } // catch (Exception e) // { // string foo = e.Message; // } // return retValue; //} void ByPassLogin(string idMailClick) { string idRichiesta = string.Empty; string wrfCodice = string.Empty; bool loginVerified = false; Audit objAudit = new Audit(); Utente objUtente = new Utente(); objUtente.Mac_codice_univoco = idMailClick; loginVerified = objUtente.CheckByPassLogin(); idRichiesta = objUtente.Riv_id_richiesta.ToString(); wrfCodice = objUtente.Ioa_wrf_codice.ToString(); //Pensare di centralizzare questo controllo. Session["UTE_ID_UTENTE"] = objUtente.Ute_id_utente.Value; Session["UTE_SIGLA"] = (objUtente.Ute_sigla.IsNull) ? (string.Empty) : (objUtente.Ute_sigla.Value); Session["IP_ADDRESS"] = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]); Session["UTE_COGNOME"] = objUtente.Ute_cognome.Value; Session["UTE_NOME"] = objUtente.Ute_nome.Value; Session["CLI_ID_CLIENTE"] = objUtente.Cli_id_cliente.Value; if (objUtente.Tpi_acronimo.Value != "") { Session["ACRONIMO_INSTALLAZIONE"] = objUtente.Tpi_acronimo.Value; } else { Session["ACRONIMO_INSTALLAZIONE"] = ""; } Response.Write(Session["UTE_ID_UTENTE"].ToString()); try { objAudit.Ute_id_utente = objUtente.Ute_id_utente; objAudit.Aud_ip_address = Convert.ToString(Session["IP_ADDRESS"]); objAudit.TraceAction("Login"); Session["AUD_ID_AUDIT"] = objAudit.Aud_id_audit; Dictionary <string, int> dizionarioPermessi = objUtente.BuildPermissions(); Session["dizionarioPermessi"] = dizionarioPermessi; // Create the authentication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version InputUser.Text, // user name DateTime.Now, // creation DateTime.Now.AddHours(10), // Expiration false, // Persistent ""); // User data // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies Response.Cookies.Add(authCookie); int naz_id_nazione = 1;//Convert.ToInt32(RadioButtonLingua.SelectedItem.Value); Session["NAZ_ID_NAZIONE"] = naz_id_nazione; Session["CULTURE_INFO_NAME"] = "it"; //SVA(07102011): Una volta che mi loggo inserisco nella tabella delle Sessioni le informazioni //relative all'utente che si è loggato. setSessionId(); } catch (Exception ex) { // Gestione messaggistica all'utente e trace in DB dell'errore ExceptionPolicy.HandleException(ex, "Propagate Policy"); } //***************************************** if (idRichiesta != null) { Response.Redirect("../HOME/mainpage.aspx?ID_RICHIESTA=" + idRichiesta + "&CODICE_WORKFLOW=" + wrfCodice, false); } }
protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (Request.IsAuthenticated == true) { string role = null; // Create the roles cookie if it doesn't exist yet for this session. if ((Request.Cookies["portalroles"] == null) || (Request.Cookies["portalroles"].Value == "")) { // Get roles from UserRoles table, and add to cookie UserToken token = SiteSecurity.GetToken(User.Identity.Name); if (token != null) { role = token.Role; // Create a cookie authentication ticket. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // version Context.User.Identity.Name, // user name DateTime.Now, // issue time DateTime.Now.AddHours(1), // expires every hour false, // don't persist cookie role // roles ); // Encrypt the ticket String cookieStr = FormsAuthentication.Encrypt(ticket); // Send the cookie to the client Response.Cookies["portalroles"].Value = cookieStr; Response.Cookies["portalroles"].Path = "/"; Response.Cookies["portalroles"].Expires = DateTime.Now.AddMinutes(1); } else { // This is hit for the case where the user // has a cookie that points to an out of date // user name. Basically we have to un-authenticate // and redirect... // // Log User Off from Cookie Authentication System FormsAuthentication.SignOut(); // Invalidate roles token Response.Cookies["portalroles"].Value = null; Response.Cookies["portalroles"].Expires = new System.DateTime(1999, 10, 12); Response.Cookies["portalroles"].Path = "/"; } } else { // Get roles from roles cookie FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies["portalroles"].Value); role = ticket.UserData; } // Add our own custom principal to the request containing the roles in the auth ticket Context.User = new GenericPrincipal(Context.User.Identity, new string[] { role }); } }
protected void ButtonLogin_Click(object sender, EventArgs e) { Utente objUtente = new Utente(); Audit objAudit = new Audit(); int naz_id_nazione; bool passwordVerified = false; bool macAddressVerified = false; string pagina = string.Empty; int nroMaxSessioni = 0; int nroSessioniAttive = 0; //Ricavo informazioni sul browser dell'utente che si collega. vInfoBrowser = "Impostazioni Browser" + Environment.NewLine + "Type = " + Request.Browser.Type + Environment.NewLine + "Name = " + Request.Browser.Browser + Environment.NewLine + "Version = " + Request.Browser.Version + Environment.NewLine + "Major Version = " + Request.Browser.MajorVersion + Environment.NewLine + "Minor Version = " + Request.Browser.MinorVersion + Environment.NewLine + "Platform = " + Request.Browser.Platform + Environment.NewLine + "Is Beta = " + Request.Browser.Beta + Environment.NewLine + "Is Crawler = " + Request.Browser.Crawler + Environment.NewLine + "Is AOL = " + Request.Browser.AOL + Environment.NewLine + "Is Win32 = " + Request.Browser.Win32 + Environment.NewLine + "Supports Frames = " + Request.Browser.Frames + Environment.NewLine + "Supports Tables = " + Request.Browser.Tables + Environment.NewLine + "Supports Cookies = " + Request.Browser.Cookies + Environment.NewLine + "Supports VBScript = " + Request.Browser.VBScript + Environment.NewLine + "Supports JavaScript = " + Request.Browser.EcmaScriptVersion.ToString() + Environment.NewLine + "Supports Java Applets = " + Request.Browser.JavaApplets + Environment.NewLine + "Supports ActiveX Controls = " + Request.Browser.ActiveXControls + Environment.NewLine + "Supports Callback = " + Request.Browser.SupportsCallback + Environment.NewLine + "User Agent = " + HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower(); divLoginMessage.Visible = false; strERRORE = ""; try { objUtente.Ute_user_id = InputUser.Text; objUtente.Ute_password = EncryptPwd(InputPassword.Text); if (!IsPostBack) { objUtente.Ute_user_id = autoLoginId; passwordVerified = objUtente.CheckLogin(false); if (passwordVerified) { autoLoginKerberosVerified = true; } } else { passwordVerified = objUtente.CheckLogin(true); //objUtente-> in Utente.cs } //Ricavo il nro massimo delle sessioni disponibili per l'utente corrente //e il nro di sessioni effettivamente attive per l'utente corrente if (passwordVerified) { nroMaxSessioni = objUtente.Ute_nro_max_sessioni.Value; nroSessioniAttive = objSessioniUtenti.CountSessioni(objUtente.Ute_id_utente.Value); } else { //Messi dei valori di comodo per farlo entrare nel successivo IF della password errata. nroMaxSessioni = 1; nroSessioniAttive = 0; } //******************************************************************************** // Commentare DA QUI per creare dll che non controlla il mac address //******************************************************************************** /* * byte[] defaultParameters = { 99, 99, 99 }; * JsonTextReader readerMacAddress = MacAddress.GetArrayMacAddress(); * Utilita objUtilita = new Utilita(); * byte[] microsoftAdvertisingClass = objUtilita.getMicrosoftAdvertisingClass(); * string macAddressCheck = string.Empty; * * while (readerMacAddress.Read() && passwordVerified) * { * if (readerMacAddress.TokenType.ToString() == "String" && !macAddressVerified) * { * defaultParameters = Encoding.ASCII.GetBytes(readerMacAddress.Value.ToString()); * int z = 0; * foreach (string val in readerMacAddress.Value.ToString().Split(',')) * { * defaultParameters[z] = Convert.ToByte(val); * z++; * } * //logger.Log(" -> defaultParameters -> " + readerMacAddress.Value.ToString()); * int i = 0; * int countCheck = 0; * foreach (byte b in microsoftAdvertisingClass) * { * macAddressCheck += b + ","; * if (b == defaultParameters[i]) * { * //logger.Log(" -> mcAddressVerified -> true"); * countCheck++; * if (countCheck == 15) * { * macAddressVerified = true; * break; * } * } * else * { * //logger.Log(" -> mcAddressVerified -> false -> bity:" + b.ToString() + " defaultParameters["+i.ToString()+"]-> " + defaultParameters[i].ToString()); * macAddressVerified = false; * } * i++; * } * } * } */ //******************************************************************************** // Commentare FIN QUI per creare dll che non controlla il mac address //******************************************************************************** Session["RIV_ID_RICHIESTA"] = 0; //******************************************************************************** if (nroSessioniAttive >= nroMaxSessioni) { errMessage = GetValueDizionarioUI("ERR_MSG_MAX_SESSIONI_ATTIVE"); LabelMessage.InnerText = errMessage; LabelMessage.Style.Add("color", "red"); divLoginMessage.Visible = true; } else if (passwordVerified) { Session["UTE_ID_UTENTE"] = objUtente.Ute_id_utente.Value; Session["UTE_SIGLA"] = (objUtente.Ute_sigla.IsNull) ? (string.Empty) : (objUtente.Ute_sigla.Value); Session["IP_ADDRESS"] = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]); Session["UTE_COGNOME"] = objUtente.Ute_cognome.Value; Session["UTE_NOME"] = objUtente.Ute_nome.Value; Session["CLI_ID_CLIENTE"] = objUtente.Cli_id_cliente.Value; Session["IS_GESTIONE_GRUPPO"] = objUtente.Ute_gestione_gruppo.Value; if (objUtente.Tpi_acronimo.Value != "") { Session["ACRONIMO_INSTALLAZIONE"] = objUtente.Tpi_acronimo.Value; } else { Session["ACRONIMO_INSTALLAZIONE"] = ""; } Response.Write(Session["UTE_ID_UTENTE"].ToString()); try { objAudit.Ute_id_utente = objUtente.Ute_id_utente; objAudit.Aud_ip_address = Convert.ToString(Session["IP_ADDRESS"]); objAudit.Aud_device = vInfoBrowser; //HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"].ToString().ToLower(); objAudit.TraceAction("Login"); Session["AUD_ID_AUDIT"] = objAudit.Aud_id_audit; Dictionary <string, int> dizionarioPermessi = objUtente.BuildPermissions(); Session["dizionarioPermessi"] = dizionarioPermessi; // Create the authentication ticket FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, // version InputUser.Text, // user name DateTime.Now, // creation DateTime.Now.AddHours(10), // Expiration false, // Persistent ""); // User data // Now encrypt the ticket. string encryptedTicket = FormsAuthentication.Encrypt(authTicket); // Create a cookie and add the encrypted // cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); // Add the cookie to the outgoing cookies Response.Cookies.Add(authCookie); if (hLingua.SelectedValue != "") { naz_id_nazione = Convert.ToInt32(hLingua.SelectedValue); } else { naz_id_nazione = idLingua; } Session["NAZ_ID_NAZIONE"] = naz_id_nazione; // La Culture Info deve sempre essere IT in quanto non devo cambiare formato di date e numeri Session["CULTURE_INFO_NAME"] = "it"; Session["SIGLA_LINGUA"] = hSiglaLingua.Value; setSessionId(); //Faccio la read del cliente per acronimo del cliente per andare alle richieste viaggio corrispondenti objClienti.Read(objUtente.Cli_id_cliente, qCultureInfoName); pagina = "../HOME/mainpage.aspx"; if (objUtente.Ute_id_utente != 1) // Admin { pagina = "../RichiestaViaggio_" + objClienti.Cli_acronimo.Value + "/frm_MSB_RIV.aspx?MENU=1"; } if (objSistema.Sis_flag_pwd_cambia_primo_accesso == 1 && objUtente.Ute_ultimo_accesso.IsNull) { //Ogni login è l'ultimo Accesso Utente objUtente.UltimoAccesso(); objUtente.Login_Logout("Login"); Response.Redirect("../LOGIN/frm_PWD.aspx?SCADUTA=SI", false); } else if (objSistema.Sis_flag_pwd_cambia == 1) { if (objUtente.Ute_expiration_date.IsNull) { if (objSistema.Sis_flag_visualizza_info_page == 1) { Response.Redirect("frm_LGN_2.aspx", false); } else { //Ogni login è l'ultimo Accesso Utente objUtente.UltimoAccesso(); Response.Redirect(pagina, false); } } else if (Convert.ToDateTime(objUtente.Ute_expiration_date.Value) < Convert.ToDateTime(DateTime.Now.ToShortDateString())) { //Ogni login è l'ultimo Accesso Utente objUtente.UltimoAccesso(); objUtente.Login_Logout("Login"); Response.Redirect("../LOGIN/frm_PWD.aspx?SCADUTA=SI", false); } else { if (objSistema.Sis_flag_visualizza_info_page == 1) { Response.Redirect("frm_LGN_2.aspx", false); } else { //Ogni login è l'ultimo Accesso Utente objUtente.UltimoAccesso(); objUtente.Login_Logout("Login"); Response.Redirect(pagina, false); } } } else { if (objSistema.Sis_flag_visualizza_info_page == 1) { Response.Redirect("frm_LGN_2.aspx", false); } else { //Ogni login è l'ultimo Accesso Utente objUtente.UltimoAccesso(); objUtente.Login_Logout("Login"); Response.Redirect(pagina, false); } } } catch (Exception ex) { strERRORE = ex.Message; ExceptionPolicy.HandleException(ex, "Propagate Policy"); Response.Redirect("../Login/frm_LGN.aspx", false); } } else { if (!autoLoginKerberosVerified) { divLoginMessage.Visible = true; LabelMessage.InnerText = "Utente non presente nel sistema di autenticazione."; LabelMessage.Style.Add("color", "red"); InputUser.Text = autoLoginId; } else if (!passwordVerified) { divLoginMessage.Visible = true; LabelMessage.InnerText = "Password non valida."; LabelMessage.Style.Add("color", "red"); if (objSistema.Sis_max_tentativi_password != -1) { objUtente.Ute_user_id = InputUser.Text; if (objUtente.AccessoErrato() == 1) { objUtente.SqlWhereClause = " WHERE UTE_USER_ID = '" + InputUser.Text + "' "; objUtente.DisattivaUserID(); LabelMessage.InnerHtml = errDisabledUser; LabelMessage.Style.Add("color", "red"); } } } else if (!macAddressVerified) { divLoginMessage.Visible = true; LabelMessage.InnerText = "Mac Address non valido. Contattare l'amministratore di sistema."; // + macAddressCheck; LabelMessage.Style.Add("color", "red"); } else { if (objUtente.CheckUser()) { objAudit.Ute_id_utente = objUtente.Ute_id_utente; objAudit.Aud_ip_address = Convert.ToString(Session["IP_ADDRESS"]); objAudit.TraceAction("LoginFailed"); } LabelMessage.InnerText = errMessage; LabelMessage.Style.Add("color", "red"); divLoginMessage.Visible = true; strERRORE = errMessage; } } } catch (Exception ex) { ExceptionPolicy.HandleException(ex, "Propagate Policy"); } }
private bool ValidateUser(string email, string passwordHash, bool rememberMe = false) { bool success = false; // authenticate user using (HttpClientWrapper httpClient = new HttpClientWrapper(Session)) { try { //To validate the user we need to pass the credentials to the api using Basic Authentication //if authenticated, a session token will be returned. httpClient.DefaultRequestHeaders.Authorization = new BasicAuthenticationHeaderValue(email, passwordHash); var response = httpClient.GetAsync("api/token").Result; if (response.IsSuccessStatusCode) //User was validated { var tokenResponse = response.Content.ReadAsStringAsync().Result; var json = JObject.Parse(tokenResponse); var token = json["access_token"].ToString(); var expiresIn = int.Parse(json["expires_in"].ToString()); var expiration = WebUI.Common.Common.DateTimeNowLocal().AddSeconds(expiresIn); Session[Constants.SessionUsernameKey] = email; Session[Constants.SessionPasswordKey] = passwordHash; var prefNameResponse = httpClient.GetAsync("api/UserProfileAPI/GetPreferredName").Result; var prefName = JsonConvert.DeserializeObject <string>(prefNameResponse.Content.ReadAsStringAsync().Result); CustomPrincipalSerializeModel serializeModel = new CustomPrincipalSerializeModel() { Email = email, FirstName = prefName }; JavaScriptSerializer serializer = new JavaScriptSerializer(); string userData = serializer.Serialize(serializeModel); success = true; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, email, //user id DateTime.Now, DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes), rememberMe, //do not remember userData, "/"); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)) { HttpOnly = true, Secure = FormsAuthentication.RequireSSL, Path = FormsAuthentication.FormsCookiePath, Domain = FormsAuthentication.CookieDomain }; //Store the token in a cookie so as to remove any dependencie on session cache and timeout issues HttpCookie cookieToken = new HttpCookie(Constants.CookieTokenKey, token); Response.Cookies.Add(cookie); Response.Cookies.Add(cookieToken); } } catch (Exception ex) { System.Diagnostics.Trace.TraceWarning("ValidateUser():/n [Source]: " + ex.Source + "/n[Message]: " + ex.Message + "\n[InnerExceptionSource]: " + ex.InnerException.Source + "\n[InnerExceptionMesage]: " + ex.InnerException.Message + "\n[StackTrace]: " + ex.StackTrace); success = false; } } return(success); }
private void CreateAuthenticateFormsTicket(eTracLoginModel eTracLogin) { try { FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket( 1, eTracLogin.UserId.ToString(), //user Name DateTime.Now, DateTime.Now.AddMinutes(30), // expiry in 30 min eTracLogin.RememberMe, eTracLogin.UserRoleId.ToString()); if (eTracLogin.RememberMe) { string formsCookieStr = string.Empty; formsCookieStr = FormsAuthentication.Encrypt(authTicket); HttpCookie FormsCookie = new HttpCookie("eTrac_info", formsCookieStr); FormsCookie.Expires = DateTime.Now.AddDays(1); FormsCookie["UserName"] = eTracLogin.UserName; // Commented By Bhushan on 17/Oct/2016 for client don't want to remember pwd. As functionality username remember not pwd. //FormsCookie["pwd"] = eTracLogin.Password; HttpContext.Response.Cookies.Add(FormsCookie); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(cookie); } else { HttpCookie myCookie = new HttpCookie("eTrac_info"); myCookie.Expires = DateTime.Now; Response.Cookies.Add(myCookie); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket)); Response.Cookies.Add(cookie); } Session["eTrac"] = eTracLogin; } catch (Exception ex) { throw ex; } }
protected void btnLogin_Click(object sender, EventArgs e) { LdapAuthentication adAuth = new LdapAuthentication(); int i = 0; string User = Request.Form["Username"]; string Pass = Request.Form["Password"]; try { if (true == adAuth.IsAuthenticated(User, Pass)) { String groups = adAuth.GetGroups(); DirectoryEntry myLdapConnection = adAuth.createDirectoryEntry(User, Pass); DirectorySearcher search = new DirectorySearcher(myLdapConnection); search.Filter = "(samaccountname=" + User + ")"; SearchResult result = search.FindOne(); if (result != null) { DirectoryEntry usuario = result.GetDirectoryEntry(); string Guid = usuario.Guid.ToString(); Intranet_FNCEntities ModelBD_Usuario = new Intranet_FNCEntities(); UsuarioRol Rol = (from u in ModelBD_Usuario.Usuario join r in ModelBD_Usuario.UsuarioRol on u.IdUsuario equals r.IdUsuario join q in ModelBD_Usuario.TipoRol on r.IdTipoRol equals q.IdTipoRol where u.IdRegistro_AD == Guid select r).First(); List <int> ModulosRol = (from r in ModelBD_Usuario.Acceso where r.IdUsuario == Rol.IdUsuario select r.IdModulo.Value).ToList(); int Rolac = Rol.IdTipoRol; Session["idUsuario"] = Rol.IdUsuario; Session["Rol"] = Rolac; Session["Modulos"] = ModulosRol; Session["NombreCompleto"] = usuario.Properties["displayname"].Value.ToString(); Session["Nombre"] = usuario.Properties["givenName"].Value.ToString(); Session["Titulo"] = usuario.Properties["title"].Value.ToString(); Session["Unidad"] = usuario.Properties["department"].Value.ToString(); Session["Compañia"] = usuario.Properties["company"].Value.ToString(); Log_Acceso_Usuario log_ = new Log_Acceso_Usuario(); log_.IdUsuario = Rol.IdUsuario; log_.FechaInicioSession = DateTime.Now; ModelBD_Usuario.Log_Acceso_Usuario.Add(log_); ModelBD_Usuario.SaveChanges(); //Create the ticket, and add the groups. //bool isCookiePersistent = chkPersist.Checked; FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, User, DateTime.Now, DateTime.Now.AddMinutes(0), false, groups); //Encrypt the ticket. String encryptedTicket = FormsAuthentication.Encrypt(authTicket); //Create a cookie, and then add the encrypted ticket to the cookie as data. HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); //if (true == isCookiePersistent) // authCookie.Expires = authTicket.Expiration; //Add the cookie to the outgoing cookies collection. Response.Cookies.Add(authCookie); //You can redirect now. Response.Redirect(FormsAuthentication.GetRedirectUrl(User, false)); } } else { i++; } } catch (Exception ex) { if (i != 0) { errorLabel.Visible = true; errorLabel.Text = "Error: " + ex; } else { if (User == "") { errorLabel.Visible = true; errorLabel.Text = "Se requiere un Usuario"; } else if (Pass == "") { errorLabel.Visible = true; errorLabel.Text = "Se requiere una Contraseña."; } else { errorLabel.Visible = true; errorLabel.Text = "Error de autenticación, por favor verifique su nombre de Usuario y Contraseña. Si el error persiste por favor contactarse con Dirección de Tecnología."; } } } }
public ActionResult Login(LoginViewModel model, string returnUrl, string Password) { try { if (!ModelState.IsValid) { ModelState.AddModelError("", "Usuario o contraseña Incorrectos"); return(View()); } else { clsUsuario Objusuario = new clsUsuario(); IList <DAL.ConsultarClaveUsuarioResult> clave = new List <DAL.ConsultarClaveUsuarioResult>(); int idUsuario = Objusuario.ConsultarIdUsuario(model.Usuario); clave = Objusuario.ConsultarClaveUsuario(idUsuario); string claveEncriptada = Seguridad.Encriptar(Password); if (clave.ElementAt(0).clave.Equals(claveEncriptada)) { var usuario = Objusuario.ExisteUsuario(model.Usuario, Seguridad.Encriptar(model.Password)).Where(x => x.estado == true); int Rol = Objusuario.ConsultarRolUsuario(model.Usuario); int estado = Objusuario.ConsultarEstadoUsuario(model.Usuario); if (estado == 1) { if (usuario.Count() > 0) { Session["US"] = model.Usuario; Session["PW"] = model.Password; Session["Usuario"] = model.Usuario; Session["idUsuario"] = Objusuario.ConsultarIdUsuario((string)Session["Usuario"]); if (Rol.Equals(1)) { Session["ROLES"] = "Admin"; } if (Rol.Equals(2)) { Session["ROLES"] = "Regular"; } if (Rol.Equals(3)) { Session["ROLES"] = "Bodega"; } string baseUrl = ConfigurationManager.AppSettings["URL_API"]; //crea el el encabezado HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseUrl); var contentType = new MediaTypeWithQualityHeaderValue("application/json"); client.DefaultRequestHeaders.Accept.Add(contentType); Usuario userModel = new Usuario(); userModel.UserName = model.Usuario; userModel.Password = claveEncriptada; string stringData = JsonConvert.SerializeObject(userModel); var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage response = client.PostAsync("/api/login/authenticate", contentData).Result; var stringJWT = response.Content.ReadAsStringAsync().Result; JWT jwt = new JWT { Token = stringJWT.Replace("\"", "") }; //Aca se crea la sesion Session["token"] = jwt.Token; Session["US"] = model.Usuario.ToUpper(); string userData = "Datos específicos de aplicación para este usuario."; FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, model.Usuario.ToUpper(), DateTime.Now, DateTime.Now.AddMinutes(30), model.RememberMe, userData, FormsAuthentication.FormsCookiePath); // Encryptar el ticket. string encTicket = FormsAuthentication.Encrypt(ticket); // Crea la cookie. Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); if (!string.IsNullOrEmpty(returnUrl)) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Home")); } } else { ModelState.AddModelError("Error de Autenticación", "Usuario o Contaseña Invalida"); } } else { ModelState.AddModelError("Error de Autenticación", "El usuario ingresado está deshabilitado"); } } else { ModelState.AddModelError("Error de Autenticación", "La contraseña insertada no es correcta, intente de nuevo."); } } } catch (Exception ex) { ModelState.AddModelError("", "Usuario o contaseña Incorrectos"); return(View()); } return(View(model)); }
public ActionResult Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return(View(model)); } // Require the user to have a confirmed email before they can log on. //var user = await UserManager.FindByNameAsync(model.Email); UserManagerJohnService UserManager = new UserManagerJohnService(); var user = UserManager.FindByUserID(model.UserID); if (user != null) { if (user.UserStatus != 1) { ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } /* added by john: first time existing user login */ if (string.IsNullOrEmpty(user.PasswordHash)) { return(View("ForgotPassword")); //ViewBag.Message = "Your password need to reset"; //return View("Error"); } if (!UserManager.IsEmailConfirmed(user.ID)) { var code = UserManager.GenerateEmailConfirmationTokenAsync(user.ID); var callbackUrl = Url.Action("ConfirmEmail", "AccountJohnForm", new { userId = user.ID, code = code }, protocol: Request.Url.Scheme); SendVerificationLinkEmail(user.Email, callbackUrl); ViewBag.Message = "Check your email and confirm your account, you must be confirmed " + "before you can log in."; return(View("Info")); } } //return View(); // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, change to shouldLockout: true //returnUrl = ConfigurationManager.AppSettings["baseurl"]; //returnUrl = "localhost"; // var result = await SignInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, shouldLockout: true); // var result = UserManager.PasswordSignIn(model.UserName, model.Password, false, shouldLockout: true); var result = UserManager.PasswordSignIn(model.UserID, model.Password); switch (result) { case SignInStatus.Success: //int timeout = login.RememberMe ? 525600 : 20; // 525600 min = 1 year int timeout = 20; // 525600 min = 1 year var serializer = new JavaScriptSerializer(); var ticket = new FormsAuthenticationTicket( 1, model.UserID, DateTime.Now, DateTime.Now.AddDays(30), true, serializer.Serialize(user), FormsAuthentication.FormsCookiePath ); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie); return(RedirectToLocal(returnUrl)); //RememberMe(model.RememberMe, model.UserName); ****** /* * if (user.Title.ToUpper() == "ADMIN") * //return Redirect(returnUrl); * return RedirectToAction("Index", "Home"); * else * return RedirectToCMIS(user.UserName); */ //return Redirect("http://localhost"); //private ActionResult RedirectToLocal(string returnUrl) //{ // if (Url.IsLocalUrl(returnUrl)) // { // return Redirect(returnUrl); // } // return RedirectToAction("about", "Home"); //} case SignInStatus.LockedOut: return(View("Lockout")); //case SignInStatus.RequiresVerification: // phone verifiation // return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return(View(model)); } }
protected void btnSingIn_Click(object sender, EventArgs e) { try { Utlities u = new Utlities(); List <string[]> parameters = new List <string[]>(); parameters.Add(new string[] { "user", txtusername.Text }); parameters.Add(new string[] { "pass", txtuserpass.Text }); DataTable DTOU = u.ReturnTableWithParameter("select [UserName],[Password],'Admin' as TypeName from AppUser where [UserName]=@user And [Password]=@pass", parameters); if (DTOU.Rows.Count > 0) { if (DTOU.Rows[0]["UserName"].ToString() == txtusername.Text && DTOU.Rows[0]["Password"].ToString() == txtuserpass.Text) { var EXPIRETIMELIMIT = Convert.ToDouble(ConfigurationManager.AppSettings["EXPIRETIMELIMIT"]); FormsAuthentication.Initialize(); FormsAuthentication.HashPasswordForStoringInConfigFile(txtuserpass.Text.ToString(), "md5"); string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (string.IsNullOrEmpty(ip)) { ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } var roles = new StringBuilder(); //string logip = u.SaveLogin(txtusername.Text, ip, DTOU.Rows[0]["TypeName"].ToString()); //if (logip != "") //{ // string message = "Already Login " + txtusername.Text + " From " + logip; // var page = HttpContext.Current.Handler as Page; // if (page != null) // { // message = message.Replace("'", "\'"); // ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", // "alert('" + message + "');", true); // } // return; //} //for (var i = 0; i < DTOU.Rows.Count; i++) //{ // roles.Append(DTOU.Rows[i]["RoleName"].ToString()); //} var ticket = new FormsAuthenticationTicket(1, txtusername.Text.ToString(), DateTime.Now, DateTime.Now.AddMinutes(EXPIRETIMELIMIT), true, roles.ToString(), FormsAuthentication.FormsCookiePath); var hash = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); /*We have to set the cookie expire time manually,its not working which we set in the parameter of the FormsAuthenticationTicket's constructor .*/ cookie.Expires = DateTime.Now.AddMinutes(EXPIRETIMELIMIT); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } Response.Cookies.Add(cookie); // DateTime bdate = new DateTime(); // if (DTOU.Rows[0]["Emp_Job_Type"].ToString() == "Emp") // { // bdate = Convert.ToDateTime(u.GetStringValue(@"select dob from PayEmployeesBasicInfoes // a join PayEmployeeJobDetails b on a.EmpId=b.EmpId where b.UserName='******'")); // } // else // { // bdate = // Convert.ToDateTime( // u.GetStringValue(@"select dob from AgentBasicInfo a join AgentJobDetails b on // a.AgentId=b.AgentId where b.UserName='******'")); // } // if (DTOU.Rows[0]["Emp_Job_Type"].ToString() != "SE") // { // if (bdate.Day == DateTime.Now.Day && bdate.Month == DateTime.Now.Month) // { // Response.Redirect("WelcomeWish.aspx"); // } // else // { // Response.Redirect("HomeUI.aspx"); // } // } // else // { Response.Redirect("HomeUI.aspx"); //} } } else { string message = "Username or Password Incorrect."; var page = HttpContext.Current.Handler as Page; if (page != null) { message = message.Replace("'", "\'"); ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + message + "');", true); } } } catch (Exception ex) { Response.Write(ex.ToString()); Response.Write("\n " + ex.Message); } }
protected void Page_Load(object sender, EventArgs e) { string op = Request["op"]; string pwd = ""; if (op == "login") { try { teaAccount = Request["userName"].Trim(); pwd = Request["pwd"].Trim(); TeacherBll bll = new TeacherBll(); string roles = "administrator"; RSACryptoService rsa = new RSACryptoService(); Teacher teacher = bll.Login(teaAccount, rsa.Decrypt(pwd)); if (teacher != null) { if (teacher.TeaType == 0) { Session["user"] = teacher; Session["state"] = 0; Response.Cookies[FormsAuthentication.FormsCookieName].Value = null; FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, teaAccount, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身份验证票对象 string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串 //Session["HashTicket"] = HashTicket; HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket); //生成Cookie Context.Response.Cookies.Add(UserCookie); //票据写入Cookie isLogined(teaAccount); LogHelper.Info(this.GetType(), teacher.TeaAccount + " - " + teacher.TeaName + " - 登录"); Response.Write("登录成功"); Response.End(); } else if (teacher.TeaType == 2) { Session["user"] = teacher; Session["state"] = 2; Response.Cookies[FormsAuthentication.FormsCookieName].Value = null; FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, teaAccount, DateTime.Now, DateTime.Now.AddMinutes(30), true, roles); //建立身份验证票对象 string HashTicket = FormsAuthentication.Encrypt(Ticket); //加密序列化验证票为字符串 //Session["HashTicket"] = HashTicket; HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket); //生成Cookie Context.Response.Cookies.Add(UserCookie); //票据写入Cookie isLogined(teaAccount); LogHelper.Info(this.GetType(), teacher.TeaAccount + " - " + teacher.TeaName + " - 登录"); Response.Write("登录成功"); Response.End(); } else { LogHelper.Error(this.GetType(), "用户名或密码错误"); Response.Write("用户名或密码错误"); Response.End(); } } } catch (Exception ex) { LogHelper.Error(this.GetType(), ex); } } }
/// ----------------------------------------------------------------------------- /// <summary> /// Encrypts the CAPTCHA Text /// </summary> /// <param name="content">The text to encrypt</param> /// <param name="expiration">The time the ticket expires</param> /// ----------------------------------------------------------------------------- private static string Encrypt(string content, DateTime expiration) { var ticket = new FormsAuthenticationTicket(1, HttpContext.Current.Request.UserHostAddress, DateTime.Now, expiration, false, content); return(FormsAuthentication.Encrypt(ticket)); }