protected void btnLoginAsStaff_Click(object sender, EventArgs e) { //get user's input string inputUserName = this.txtUserName.Text; string password = this.txtPassword.Text; if (Authentication.ValidateUser(inputUserName, password, "Staff")) { // initialize FormsAuthentication FormsAuthentication.Initialize(); // create a new ticket used for authentication FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, inputUserName, DateTime.Now, DateTime.Now.AddMinutes(15), this.chekRememberMe.Checked, "userData"); // encrypt the cookie using the machine key for secure transport string encTicket = FormsAuthentication.Encrypt(authTicket); // create and add the cookies to the list for outgoing response HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); Session["username"] = inputUserName; Session["staff"] = true; // flag for staff access Response.Redirect(@"~/Staff/Staff.aspx"); } else { this.lblLoginError.Text = "Invalid Credentials: Please try again."; } }
/// <summary> /// Login as member /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnLoginAsMember_Click(object sender, EventArgs e) { //get user's input string inputUserName = this.txtUserName.Text; string password = this.txtPassword.Text; if (Authentication.ValidateUser(inputUserName, password, "Member")) { ////RedirectFromLoginPage method to automatically generate the forms authentication cookie and redirect the user to an appropriate page in the //var isPersistentCooke = chekRememberMe.Checked; //FormsAuthentication.RedirectFromLoginPage(userName, isPersistentCooke); // initialize FormsAuthentication FormsAuthentication.Initialize(); // create a new ticket used for authentication FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, inputUserName, DateTime.Now, DateTime.Now.AddMinutes(15), this.chekRememberMe.Checked, "userData"); // encrypt the cookie using the machine key for secure transport string encTicket = FormsAuthentication.Encrypt(authTicket); // create and add the cookies to the list for outgoing response HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); Session["username"] = inputUserName; Response.Redirect(@"~/Member/Member.aspx"); } else { this.lblLoginError.Text = "Invalid Credentials: Please try again."; } }
// // POST: /Account/LogOff public ActionResult LogOff() { WebSecurity.Logout(); // Drop all the information held in the session Session.Clear(); Session.Abandon(); FormsAuthentication.Initialize(); string strRole = String.Empty; FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1, "", DateTime.Now, DateTime.Now.AddMinutes(-30), false, strRole, FormsAuthentication.FormsCookiePath); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat))); //// clear authentication cookie //HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, ""); //cookie1.Expires = DateTime.Now.AddYears(-1); //Response.Cookies.Add(cookie1); //// clear session cookie //HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", ""); //cookie2.Expires = DateTime.Now.AddYears(-1); //Response.Cookies.Add(cookie2); return(RedirectToAction("Login")); }
private static FormsAuthenticationTicket GetTicket(User user) { if (user == null) { return(null); } const int version = 1; const int days = 7; const char separator = ','; string cookieName = user.Login.Trim(); string userData = user.UserId.ToString() + separator + user.Role.Name; string cookiePath = FormsAuthentication.FormsCookiePath; DateTime currentDate = DateTime.Now; DateTime expirationDate = currentDate.AddDays(days); FormsAuthentication.Initialize(); return (new FormsAuthenticationTicket(version: version, name: cookieName, issueDate: currentDate, expiration: expirationDate, isPersistent: true, userData: userData, cookiePath: cookiePath )); }
public void Init(HttpApplication context) { FormsAuthentication.Initialize(); context.AuthenticateRequest += new EventHandler(OnAuthenticateRequest); context.EndRequest += new EventHandler(OnEndRequest); // Forms context.AuthorizeRequest += new EventHandler(OnAuthorizeRequest); }
/// <summary> /// assigns the auth-cookie to user /// </summary> public static void FormsAuthLogin(string userName, bool rememberMe, HttpContext context) { LoginUtils.ResetBruteForceCounter(context); if (!rememberMe) { FormsAuthentication.SetAuthCookie(userName, false); } else { FormsAuthentication.Initialize(); DateTime expires = DateTime.Now.AddDays(20); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, expires, // value of time out property true, // Value of IsPersistent property String.Empty, FormsAuthentication.FormsCookiePath); string encryptedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie authCookie = new HttpCookie( FormsAuthentication.FormsCookieName, encryptedTicket); authCookie.Expires = expires; HttpContext.Current.Response.Cookies.Add(authCookie); } }
static public void Initialize_delegate() { // calling Initialize without an HttpContext FormsAuthentication.Initialize(); // and that doesn't change the default values DefaultValues_delegate(); }
protected void Application_Start() { FormsAuthentication.Initialize(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); }
protected void btnAceptar_Click(object sender, EventArgs e) { try { FormsAuthentication.Initialize(); //txtUsuario.Text + "|" + Variables.IdPersonaLoggins + "|" + Variables.IdSociedad Agregar esta linea cuando se agregue becas // //El metodo AddMinutes determina que tan larga sera la sesion del usuario FormsAuthenticationTicket fat = new FormsAuthenticationTicket( 1, "admin|0|1",// Agregar esta linea cuando se agregue becas DateTime.Now, DateTime.Now.AddMinutes(Session.Timeout), false, "Administrador Sistemas",//TODO: Definir obtencion de roles, pendiente del modelo de seguridad admin|user FormsAuthentication.FormsCookiePath); var cookie = new HttpCookie( FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(fat)); cookie.Domain = ConfigurationManager.AppSettings["cookieDomain"]; Response.Cookies.Add(cookie); Response.Redirect("~/CookieOK.aspx", false); } catch (Exception ex) { Response.Redirect("~/Error/Error.aspx", false); } }
protected void Button1_Click(object sender, EventArgs e) { string userData = ""; string userName = ""; if (DropDownList1.SelectedIndex == 0) // admin { userData = "Admin"; // set userData userName = "******"; } else if (DropDownList1.SelectedIndex == 1) //customer { userData = "Customer"; // set userData userName = "******"; } // initialize FormsAuthentication FormsAuthentication.Initialize(); // create a new ticket used for authentication FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData); // encrypt the cookie using the machine key for secure transport string encTicket = FormsAuthentication.Encrypt(authTicket); // create and add the cookie to the list for outgoing response HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); Response.Redirect("/Admin/WebForm1.aspx"); }
public static bool LoginUser(string _username, bool _rememberAccount) { LogoutUser(); FormsAuthentication.Initialize(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, MEMBER_PREFIX + _username, DateTime.Now, DateTime.Now.AddMinutes(45), _rememberAccount, "", FormsAuthentication.FormsCookiePath); Trace.Write(FormsAuthentication.FormsCookiePath + FormsAuthentication.FormsCookieName); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); HttpContext.Current.Response.SetCookie(cookie); UserInfo info = UserController.GetUser(_username); if (info != null) { string _password = info.Password; HttpContext.Current.Response.Cookies.Get("name").Value = _username; HttpContext.Current.Response.Cookies.Get("pass").Value = _password; HttpContext.Current.Response.Cookies["name"].Expires = DateTime.Now.AddDays(1); HttpContext.Current.Response.Cookies["pass"].Expires = DateTime.Now.AddDays(1); return(true); } else { return(false); } }
public static void LogIn(string userName, string userData) { FormsAuthentication.Initialize(); var expiration = DateTime.Now.Add(FormsAuthentication.Timeout); var authTicket = new FormsAuthenticationTicket( 1, userName, DateTime.Now, expiration, true, userData); string encTicket = FormsAuthentication.Encrypt(authTicket); if (!FormsAuthentication.CookiesSupported) { FormsAuthentication.SetAuthCookie(encTicket, true); } else { HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = authTicket.Expiration }; HttpContext.Current.Response.Cookies.Add(authCookie); } }
protected void Entrar_Click(object sender, EventArgs e) { // VALIDAÇÃO DAS ENTRADAS if (NomeLogin.Text.Trim() == "") { Mensagem.Text = "Entre com o nome"; } else if (Senha.Text.Trim() == "") { Mensagem.Text = "Entre com a senha"; } else { if (NomeLogin.Text == "Admin" & Senha.Text == "12345") { Session["Usuario"] = "Admin"; // Inicializa a classe de autenticação do server FormsAuthentication.Initialize(); // cria o ticket de autenticação FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, "Admin", DateTime.Now, DateTime.Now.AddMinutes(30), false, "Admin", FormsAuthentication.FormsCookiePath); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))); Response.Redirect("~/Default.aspx"); } else { Mensagem.Text = "Dados de acesso invalidos"; } } }
public static void SetAuthCookie(HttpContext context, string username, string roles) { FormsAuthentication.Initialize(); DateTime expires = DateTime.Now.AddDays(14); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, expires, true, roles, FormsAuthentication.FormsCookiePath); HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); if (ticket.IsPersistent) { authCookie.Expires = ticket.Expiration; } context.Response.Cookies.Add(authCookie); FormsIdentity identity = new FormsIdentity(ticket); context.User = new GenericPrincipal(identity, roles.Split(',')); }
public void Initialize2( string cookieName, string cookieDomain, string cookiePath, bool slidingExpiration, string protection, int timeout, bool requireSSL, string validationKey, string decryptionKey, string validationMode ) { FormsAuthentication.Initialize( cookieName, cookieDomain, cookiePath, slidingExpiration, (FormsProtectionEnum)Enum.Parse(typeof(FormsProtectionEnum), protection, true), timeout, requireSSL, validationKey, decryptionKey, (FormsCryptoValidationMode)Enum.Parse(typeof(FormsCryptoValidationMode), validationMode, true) ); }
private bool RunLogin() { bool RetVal = false; FormsAuthentication.Initialize(); string username = txtUsername.Text; string password = txtPassword.Text; var mUser = new clsSchool.StaffDB().GetByEmail(username); if (mUser != null) { if (mUser.StaffId > 0 && mUser.IsActive && mUser.Password == password) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, mUser.Email, DateTime.Now, DateTime.Now.AddDays(1), true, mUser.StaffId.ToString(), FormsAuthentication.FormsCookiePath); Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))); hdfStaff.Value = mUser.StaffId.ToString(); RetVal = true; } } mUser = null; return(RetVal); }
protected void btn_login_Click(object sender, EventArgs e) { if (Page.IsValid) { string password = txt_password.Text; string email = txt_email.Text; try { DataBase db = new DataBase(); string passwordFromDB = db.ExecuteScalar( $"SELECT password FROM usersscrumshot WHERE email = '{email}'" ).ToString().ToUpper(); string passwordAsHash = GetSHA1(password); FormsAuthentication.Initialize(); if (passwordAsHash == passwordFromDB) { FormsAuthentication.RedirectFromLoginPage(email, false); } else { throw new Exception("Password is invalid."); } } catch (Exception ex) { lbl_errorMessage.Text = "Info: The username or the password are invalid."; } } }
public AccountSession Login(String sessionId, HttpContext context, int id, bool clientMode, Nullable <DateTime> expires, bool startSession) { FormsAuthentication.Initialize(); string[] roles = new string[0]; Custom.CustomServerImpl.AddCookie(context, sessionId, id, roles, expires, clientMode); return(startSession ? SessionManagement.Instance.NewSession(id, sessionId) : null); }
// GET: Account public ActionResult Login(string name) { FormsAuthentication.SignOut(); FormsAuthentication.Initialize(); FormsAuthentication.RedirectFromLoginPage(name, false); return(Redirect("http://localhost:5194/")); }
private void AthenticateAndForward() { //// Initialize FormsAuthentication (reads the configuration and gets //// the cookie values and encryption keys for the given application) FormsAuthentication.Initialize(); FormsAuthentication.HashPasswordForStoringInConfigFile(txtboxPassword.Text, "MD5"); //// you can use the above method for encrypting passwords to be stored in the database //// Execute the command string[] rolesdata = Roles.GetRolesForUser(txtboxUserName.Text); string userData = ""; foreach (string s in rolesdata) { userData += s + ","; } userData.TrimEnd(new char[] { ',', ' ' }); if (Membership.ValidateUser(txtboxUserName.Text, txtboxPassword.Text)) { //Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version txtboxUserName.Text, // Username to be associated with this ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire true, // "true" for a persistent user cookie (could be a checkbox on form) userData, // User-data (the roles from this user record in our database) FormsAuthentication.FormsCookiePath); // Path cookie is valid for //// Hash the cookie for transport over the wire string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie (it's the name specified in web.config) hash); // Hashed ticket //// Add the cookie to the list for outbound response Response.Cookies.Add(cookie); Session["role"] = rolesdata[0]; Session["Username"] = txtboxUserName.Text; //// Redirect to requested URL, or homepage if no previous page requested string returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl == null) { returnUrl = "FormMyCourse.aspx"; } //// Don't call the FormsAuthentication.RedirectFromLoginPage since it could //// replace the authentication ticket we just added... Response.Redirect(returnUrl); //FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false); } else { // Username and or password not found in our database... lblErrorMessage.Visible = true; } }
protected void btnBuyerLogin_Click(object sender, EventArgs e) { string username = txtBuyerName.Text; //string password = Encrypter.EncryptText(txtBuyerPassword.Text); string password = txtBuyerPassword.Text; tblBuyer = adpBuyer.GetDataBy(username, password); if (tblBuyer.Count == 1) { var row = tblBuyer[0]; FormsAuthentication.Initialize(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(30), chkRememberBuyer.Checked, row.role, FormsAuthentication.FormsCookiePath ); string hashedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedTicket); if (ticket.IsPersistent) { cookie.Expires = ticket.Expiration; } Response.Cookies.Add(cookie); string returnUrl = Request.QueryString["ReturnUrl"]; if (returnUrl == null) { if (row.role == "Buyer") { returnUrl = "~/Default.aspx"; } else if (row.role == "Seller") { returnUrl = "~/seller/sellerLogin.aspx"; } else { returnUrl = "~/Default.aspx"; } } Session["username"] = username; Session["role"] = row.role; Response.Redirect(returnUrl); } else { lblMessage.Text = "Login failed please try again"; } }
// Note: For an explanation of the forums authentication code used // in this function, please refer to Heath Stewart's article on Code Project: // Role-based Security with Forms Authentication // http://www.codeproject.com/aspnet/formsroleauth.asp private void LoginButton_Click(object sender, System.EventArgs e) { // If email and password are entered, try to log user on if (_emailValidator.IsValid && _passwordValidator.IsValid) { int userID = UserDB.GetUserIDFromEmail(_emailTextBox.Text, WebID); if (userID > 0) { // Get information for user with identifier userID User user = UserDB.GetUser(userID); if (user.Password == _passwordTextBox.Text) { // Record the user that is going to be logged on _userID = userID; // Initialise forms authentication FormsAuthentication.Initialize(); // Create a new ticket used for authentication DateTime expire = DateTime.Now; if (_rememberMeCheckBox.Checked) { expire = expire.AddYears(10); } else { expire = expire.AddMinutes(30); } FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version userID.ToString(), // Username associated with ticket DateTime.Now, // Date/time issued expire, // Date/time to expire _rememberMeCheckBox.Checked, // "true" for a persistent user cookie user.Roles, // 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 Page.Response.Cookies.Add(cookie); RedirectReturnURL(); } } } }
protected void Button1_Click(object sender, EventArgs e) { Label1.Text = user_select.SelectedItem.Text; // Initialize FormsAuthentication, for what it's worth FormsAuthentication.Initialize(); System.Configuration.Configuration webConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/"); System.Configuration.ConnectionStringSettings connString; connString = webConfig.ConnectionStrings.ConnectionStrings["NET-Prototype1ConnectionString"]; SqlConnection conn = new SqlConnection(connString.ConnectionString); SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT role FROM Person WHERE pnr = @pnr"; cmd.Parameters.Add("@pnr", SqlDbType.VarChar).Value = user_select.SelectedValue; conn.Open(); SqlDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { // Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version user_select.SelectedValue, // Username(Pnr) 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); // Redirect to requested URL Response.Redirect("/"); } 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! error_label.Text = "Not found. Please try again."; error_label.Visible = true; } }
///******************************************************************************* ///NOMBRE DE LA FUNCIÓN: AutentificarUsuario ///DESCRIPCIÓN: VALIDA AUTENTIFICACION ///PARAMETROS: ///CREO: ///FECHA_CREO: ///MODIFICO: ///FECHA_MODIFICO: ///CAUSA_MODIFICACIÓN: ///******************************************************************************* private String Autentificar() { Cls_Ctrl_Operaciones Controlador = new Cls_Ctrl_Operaciones(); Cls_Mdl_Usuarios Obj_Negocio = new Cls_Mdl_Usuarios(); Respuesta Obj_Respuesta = new Respuesta(); String Json_Resultado = String.Empty; String Json_Object = String.Empty; DataTable Dt_Registros = new DataTable(); String Str_Json = String.Empty; try { Json_Object = HttpUtility.HtmlDecode(HttpContext.Current.Request["Param"] == null ? String.Empty : HttpContext.Current.Request["Param"].ToString().Trim()); Obj_Negocio = JsonMapper.ToObject <Cls_Mdl_Usuarios>(Json_Object); Dt_Registros = Controlador.Consulta_Usuario(Obj_Negocio); if (Dt_Registros != null) { if (Dt_Registros.Rows.Count > 0) { if (Dt_Registros.Rows[0]["Estatus"].ToString().Trim().ToUpper() == "ACTIVO") { Obj_Respuesta.Estatus = true; Sessiones.Usuario_ID = Dt_Registros.Rows[0]["Usuario_ID"].ToString().Trim(); Sessiones.Nombre = Dt_Registros.Rows[0]["Nombre"].ToString().Trim().ToUpper(); Sessiones.Identificador = Dt_Registros.Rows[0]["Identificador"].ToString().Trim(); Sessiones.Email = Dt_Registros.Rows[0]["Email"].ToString().Trim(); Sessiones.Tipo_Usuario = Dt_Registros.Rows[0]["Tipo"].ToString().Trim(); FormsAuthentication.Initialize(); } else { Obj_Respuesta.Estatus = false; Obj_Respuesta.Mensaje = "Favor de comunicarse con el área administrativa, para activar su Login"; } } else { Obj_Respuesta.Estatus = false; Obj_Respuesta.Mensaje = "Favor de introducir sus datos correctos."; } } else { Obj_Respuesta.Estatus = false; Obj_Respuesta.Mensaje = "Favor de introducir sus datos correctos."; } } catch (Exception Ex) { Obj_Respuesta.Estatus = false; Obj_Respuesta.Mensaje = "Informe técnico - [No se encontró el servidor o éste no estaba accesible]"; } finally { Json_Resultado = JsonMapper.ToJson(Obj_Respuesta); } return(Json_Resultado); }
private static void SetAuthCookie( string userName, bool createPersistentCookie, object userData) { if (!System.Web.HttpContext.Current.Request.IsSecureConnection && FormsAuthentication.RequireSSL) { throw new HttpException("Connection not secure creating secure cookie"); } // <!> In this way, we will lose the function of cookieless //var flag = UseCookieless( // System.Web.HttpContext.Current, // false, // FormsAuthentication.CookieMode); FormsAuthentication.Initialize(); if (userName == null) { userName = string.Empty; } var cookiePath = FormsAuthentication.FormsCookiePath; var utcNow = DateTime.UtcNow; var expirationUtc = utcNow + FormsAuthentication.Timeout; var authenticationTicket = new FormsAuthenticationTicket( 2, userName, utcNow.ToLocalTime(), expirationUtc.ToLocalTime(), createPersistentCookie, JsonConvert.SerializeObject(userData), cookiePath ); var encryptedTicket = FormsAuthentication.Encrypt(authenticationTicket); if (string.IsNullOrEmpty(encryptedTicket)) { throw new HttpException("Unable to encrypt cookie ticket"); } var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { HttpOnly = true, Path = cookiePath, Secure = FormsAuthentication.RequireSSL }; if (FormsAuthentication.CookieDomain != null) { authCookie.Domain = FormsAuthentication.CookieDomain; } if (authenticationTicket.IsPersistent) { authCookie.Expires = authenticationTicket.Expiration; } System.Web.HttpContext.Current.Response.Cookies.Add(authCookie); }
protected void Enviar_Click(object sender, EventArgs e) { try { if (NomeLogin.Text.Trim() == "") { Mensagem.Text = "Preencha o campo Login"; } else if (Senha.Text.Trim() == "") { Mensagem.Text = "Preencha o campo Senha"; } else { string comando = "SELECT * FROM Funcionarios WHERE Login='******'AND Senha='" + Senha.Text + "';"; AppDatabase.OleDBTransaction db = new AppDatabase.OleDBTransaction(); db.ConnectionString = conexao; System.Data.DataTable tb = (System.Data.DataTable)db.Query(comando); if (tb.Rows.Count == 1) { Session["Codigo"] = tb.Rows[0]["Codigo"].ToString(); Session["Nome"] = tb.Rows[0]["Nome"].ToString(); // AUTENTICAÇÃO DE USUARIO FormsAuthentication.Initialize(); //Define os dados do ticket de autenticação FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, Session["Nome"].ToString(), DateTime.Now, DateTime.Now.AddMinutes(30), false, Session["Nome"].ToString(), FormsAuthentication.FormsCookiePath); // Grava o ticket no cookie de autenticação Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket))); // redirecionar para a Dasboard Response.Redirect("~/Pages/Admin/Dashboard.aspx"); } else { Mensagem.Text = "Dados Inválidos"; } } } catch (ThreadAbortException) { // IGNORE: this is normal behavior for Redirect method } catch (Exception ex) { Mensagem.Text = "Houve uma falha inesperada. Por Favor, tente novamente mais tarde"; RecoverExceptions re = new RecoverExceptions(); re.SaveException(ex); } }
/// <summary> /// Authenticates a user by creating a cookie for FormsAuthentication /// and setting the Principal and roles for immediate use. /// </summary> /// <param name="user"></param> /// <param name="persist"></param> public static void Authenticate(GreyFoxUser user, bool persist) { string hash; DateTime expireDate; FormsAuthenticationTicket authTicket; HttpCookie authCookie; // Initialize Forms Authentication FormsAuthentication.Initialize(); // Set Persistence Cookie Expirations if (persist) { expireDate = DateTime.Now.AddYears(1); } else { expireDate = DateTime.Now.AddDays(2); } // Create Ticket authTicket = new FormsAuthenticationTicket( 1, user.UserName, DateTime.Now, expireDate, persist, String.Join(",", user.Roles.RolesNamesToArray()), FormsAuthentication.FormsCookiePath); // Encrypt Ticket hash = FormsAuthentication.Encrypt(authTicket); // Set Cookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); if (persist) { authCookie.Expires = authTicket.Expiration; } // Add Cookie To Response HttpContext.Current.Response.Cookies.Add(authCookie); // Set Principal FormsIdentity ident; ident = new FormsIdentity(authTicket); GenericPrincipal principal; principal = new GenericPrincipal(ident, user.Roles.RolesNamesToArray()); HttpContext.Current.User = principal; }
/// <summary> /// register a new user with name and password /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnRegister_Click(object sender, EventArgs e) { var inputUserName = this.txtName.Text; var inputPassword = this.txtPwd.Text; // Check for invalid userName. if (string.IsNullOrEmpty(inputUserName) || string.IsNullOrEmpty(inputPassword)) { this.lblResult.Text = "Error: Please make sure you entered the username and password."; return; } var result = string.Empty; if (VerifyInputAganistImage()) { try { //call service XMLServiceRef.ServiceClient proxy = new XMLServiceRef.ServiceClient(); var encrypedPwd = MD5HashLibrary.MD5Hash.Encrypt(inputPassword); result = proxy.CreateMember(inputUserName, encrypedPwd); if (result.Contains("is created successfully at")) { // initialize FormsAuthentication FormsAuthentication.Initialize(); // create a new ticket used for authentication FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, inputUserName, DateTime.Now, DateTime.Now.AddMinutes(15), false, "userData"); // encrypt the cookie using the machine key for secure transport string encTicket = FormsAuthentication.Encrypt(authTicket); // create and add the cookies to the list for outgoing response HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); Response.Cookies.Add(faCookie); //Redirect to Member page Response.Redirect(@"~/Member/Member.aspx"); } else { this.lblResult.Text = result; } } catch (Exception ex) { result = ex.Message; } } else { this.lblResult.Text = "Error: Please make sure you entered the right image string"; } }
public static void SetAuthCookie(long userId, int userTypeId, string token) { FormsAuthentication.Initialize(); FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, userId.ToString() + "," + userTypeId, DateTime.Now, DateTime.Now.AddMonths(1), true, token); string cookiestr = FormsAuthentication.Encrypt(tkt); HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); ck.Expires = tkt.Expiration; ck.Path = FormsAuthentication.FormsCookiePath; ck.Domain = FormsAuthentication.CookieDomain; HttpContext.Current.Response.Cookies.Add(ck); }
protected void btnLogin_Click(object sender, EventArgs e) { var hash = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPass.Value + "~!@", "MD5"); ClPersonal cl = new ClPersonal(); cl.NationalCode = Securenamespace.SecureData.CheckSecurity(txtUserName.Value); cl.Pass = Securenamespace.SecureData.CheckSecurity(hash); DataSet ds = PersonalClass.GetList(cl); if (ds.Tables[0].Rows.Count != 0) { DataRow dr = ds.Tables[0].Rows[0]; Session["PersonalID"] = dr["PersonalID"].ToString(); Session["PersonaName"] = dr["FirstName"].ToString() + " " + dr["LastName"].ToString(); String userid = dr["PersonalID"].ToString(); string role = "public"; if (dr["Manage"].ToString() == "1") { role += ",Manage"; } HttpContext.Current.User = new GenericPrincipal(User.Identity, new string[] { role }); FormsAuthentication.Initialize(); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userid, DateTime.Now, DateTime.Now.AddMinutes(540), false, role, FormsAuthentication.FormsCookiePath); hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash); if (ticket.IsPersistent == true) { cookie.Expires = ticket.Expiration; } Response.Cookies.Add(cookie); // Roles.AddUserToRole(userid, role); // Roles.AddUserToRole(dr["UserName"].ToString(),"admin"); if (dr["Manage"].ToString() == "1") { Session["IsManage"] = "true"; } //// Response.Redirect("/Public/PersonalView.aspx?manage=1"); ////else Response.Redirect("/organ/PersonView.aspx"); ds.Dispose(); } else { //lblmsg.Text = "نام کاربری یا کلمه عبور اشتباه میباشد"; Utility.ShowMsg(Page, ProPertyData.MsgType.warning, "نام کاربری یا کلمه عبور اشتباه میباشد"); } }