protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { if (FormsAuthentication.CookiesSupported == true) { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { try { //let us take out the username now string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name; string roles = string.Empty; using (SEARCHSYSTEMSEntities3 entities = new SEARCHSYSTEMSEntities3()) { User user = entities.Users.SingleOrDefault(u => u.UserName == username); roles = user.Role; } //let us extract the roles from our own custom cookie //Let us set the Pricipal with our user specific details HttpContext.Current.User = new System.Security.Principal.GenericPrincipal( new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';')); } catch (Exception) { //somehting went wrong } } } }
public ActionResult Login(User model, string returnUrl) { // Lets first check if the Model is valid or not if (ModelState.IsValid) { using (SEARCHSYSTEMSEntities3 entities = new SEARCHSYSTEMSEntities3()) { string username = model.UserName; string password = model.Password; // Now if our password was enctypted or hashed we would have done the // same operation on the user entered password here, But for now // since the password is in plain text lets just authenticate directly bool userValid = entities.Users.Any(user => user.UserName == username && user.Password == password); // User found in the database if (userValid) { FormsAuthentication.SetAuthCookie(username, false); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } else { return(RedirectToAction("Index", "Dashboard")); } } else { ModelState.AddModelError("", "The user name or password provided is incorrect."); } } } // If we got this far, something failed, redisplay form return(View(model)); }