Hi I am trying to set a cookie in my mvc5 application right after user logged in, and I am expecting cookie to persist after browser is closed, but requested cookie seems to be null after I closed the browser (it works fine when I try to access right after the login).
Here is how I created the cookie:
public ActionResult Login(User u)
{
// this action is for handle post (login)
if (ModelState.IsValid) // this is check validity
{
using (RoadTexEntities rte = new RoadTexEntities())
{
var v = rte.Users.Where(a => a.UserEmail.Equals(u.UserEmail) && a.password.Equals(u.password)).FirstOrDefault();
if (v != null)
{
var checkBox = Request.Form["rememberMe"];
if (checkBox == "on")
{
string user = JsonConvert.SerializeObject(v);
HttpCookie userCookie = new HttpCookie("user");
userCookie.Values.Add("details", user);
userCookie.Expires.AddDays(1);
Response.Cookies.Add(userCookie);
}
Session["username"] = v.UserFirst;
return RedirectToAction("AfterLogin");
}
else
{
ViewBag.Message = "Invalid Login Credentials";
}
}
}
return View(u);
}
public ActionResult Index(){
HttpCookie userCookie = Request.Cookies["user"];
if (userCookie != null)
{
return RedirectToAction("AfterLogin");
}
else
{
return RedirectToAction("Login");
}
}
I already checked the similar questions and checked my browser settings, but still I am getting null when I requested the cookie.
Change it to
userCookie.Expires = DateTime.Now.AddDays(1);
because your former code would not set the expire time of the cookie.
Related
I have a login page and and a accounts controller with Login action. When I log in I get redirected to home page(which is good) but after logging in if I re visit the login page it shows the login form again (although I am logged in).
I tried check for session state values but every time I try to use it I get null reference error.
public ActionResult Login(string name, string password, string hash)
{
if (!string.IsNullOrWhiteSpace(name))
{
var user = _model.tblUsers.FirstOrDefault(x => x.username == name);
if (user != null)
{
if (user.powerLevel == 0)
{
Session["IsAdmin"] = (user.password == password);
Session["IsAuthor"] = null;
Session["IsUser"] = null;
}
else if (user.powerLevel == 1)
{
Session["IsAdmin"] = null;
Session["IsAuthor"] = (user.password == password);
Session["IsUser"] = null;
}
else if (user.powerLevel == 2)
{
Session["IsAdmin"] = null;
Session["IsAuthor"] = null;
Session["IsUser"] = (user.password == password);
}
else
{
return View("Login");
}
return RedirectToAction("Index","Posts");
}
}
return View("Login");
}
so if either of IsAdmin, IsAuthor, IsUser Session is set to true I want to get redirected to homepage. I tried check it with string.IsNullOrWhiteSpace but it doesnt work I always get false even if the Session is set to true
I have an issue with my asp.net MVC project, I am using cookies to persist user’s data
I use the following code to set cookie after successful login:
[HttpPost]
public ActionResult Index(string username,string password)
{
User user = db.Users.Where(t => t.username == username && t.password == password).SingleOrDefault();
if (user != null)
{
HttpCookie aCookie = new HttpCookie("cookie");
aCookie.Values["username"] = username;
aCookie.Values["role"] = user.role.ToString();
aCookie.Values["UserID"] = user.UserID.ToString();
aCookie.Values["route"] = "AdminReports";
aCookie.Secure = false;
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
isLogedIn = true;
return RedirectToAction("AdminReports", "Home");
}
TempData["ErrorMessage"] = "Wrong username or password!";
return View();
}
I Read the cookie using this code :
public ActionResult AdminReports()
{
Response.Write(Server.HtmlEncode(Request.Cookies["cookie"]["username"]));
// Response.Write(Request.Cookies["cookie"]["username"]);
if (Request.Cookies["cookie"] != null)
{
if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.Admin)
{
return View();
}
else if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.The70Hospitals)
{
return View("The70Hospitals");
}
else if (Convert.ToInt32(Request.Cookies["cookie"]["role"]) == (int)Enums.Role.The380Hospitals)
{
return View("The380Hospitals");
}
else
{
return View("LoginView");
}
}
else
{
return View("LoginView");
}
}
However the cookies lose its data which prevent the user to login. This case happens when I access the project remotely. However it works fine locally in the development mode and it runs normally also when I browse from the IIS (Run locally in the server)
Check your web.config file,
You can do some cookies settings in <system.web> section
<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />
use the System.Web.HttpCookie.HttpOnly property
Hope this helps.
I am using this login method to create cookies as session works fine. but cookies is not working. is there any problem here in the code regarding cookies.
[HttpPost]
public ActionResult Login(login a)
{
if (ModelState.IsValid)
{
Database1Entities1 b = new Database1Entities1();
var obj = b.registras.Where(m => m.email.Equals(a.email) && m.pass.Equals(a.pass)).FirstOrDefault();
if(obj != null)
{
FormsAuthentication.SetAuthCookie(a.email, a.RememberMe);
Session["UserID"] = obj.Id.ToString();
Session["UserName"] = obj.name.ToString();
if (a.RememberMe)
{
HttpCookie usercookie = new HttpCookie("UserIDa");
usercookie.Expires = DateTime.Now.AddMinutes(2);
usercookie.Values.Add("email",a.email);
usercookie.Values.Add("pass",a.pass);
HttpContext.Response.Cookies.Add(usercookie);
// var authTicket = new FormsAuthenticationTicket(1,a.email,DateTime.Now, DateTime.Now.AddMinutes(20), a.RememberMe,"", "/");
// HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
//Response.Cookies.Add(cookie);
//HttpCookie newcook = Request.Cookies["UserIDa"];
HttpContext.Request.Cookies.Get("UserIDa");
}
ViewBag.message = "congratz u login";
return RedirectToAction("welcome","Home");
}
else { }
}
return View(a);
}
I am trying to set my session object into cookie, so that I might not have login repeatedly. My code is like this :
[HttpPost]
public ActionResult Login(UserAccount user , [Bind(Include = "ID,NameOfSession")] SessionSave Sessions)
{
using (QuestionsDBContext db = new QuestionsDBContext())
{
var usr = db.userAccount.Single(u => u.UserName == user.UserName && u.Password == user.Password);
Session["UserID"] = usr.UserID.ToString();
Session["Username"] = usr.UserName.ToString();
if (user != null)
{
bool userAutherised = true;
if (userAutherised)
{
//create the authentication ticket
var serializer = new JavaScriptSerializer();
string userData = serializer.Serialize(usr.UserName.ToString());
var authTicket = new FormsAuthenticationTicket(
1,
usr.UserName.ToString(), //user id
DateTime.Now,
DateTime.Now.AddMinutes(20), // expiry
true, //true to remember
userData, //roles
FormsAuthentication.FormsCookiePath
);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
}
return RedirectToAction("Index");
}
else
{
ModelState.AddModelError("", "Username or Password is wrong");
}
}
return View();
}
And my index action :
[Authorize]
public ActionResult Index(string sortOrder, string searchString, string currentFilter, int? page)
{
if (Response.Cookies["Username"] != null)
{
//code here
}
}
Somehow, this code is not working. Every time I go to index page, I have to go through login. Please someone make this clear.
I try to implement forget password form in my asp.net mvc 4 project, everything works fine, but when I try to login to system with new password it told me that I have wrong password.
[HttpPost]
public ActionResult ForgetPassword(UserViewModel userModel) {
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var random = new Random();
var result = new string(
Enumerable.Repeat(chars, 8)
.Select(s => s[random.Next(s.Length)])
.ToArray());
User user = _userRepo.GetUserByEmail(userModel.Email);
if (user == null) {
ViewBag.Error = Resources.Account.userEmailNotExist;
return View(userModel);
}
String newHashedPassword = Crypto.HashPassword(result);
user.Password = newHashedPassword;
user.LastPasswordChangedDate = DateTime.UtcNow;
_userRepo.SaveChanges();
string enMessage = "Your new password: " + result;
var httpCookie = Request.Cookies["lang"];
if (httpCookie != null && httpCookie.Value == "en") {
_mailHelper.SendEmail(userModel.Email, "New password", enMessage);
}
return RedirectToAction("ConfirmPasswordChange", "Account");
}
Login form:
[HttpPost]
public ActionResult Login(UserViewModel user) {
var users = _userRepo.GetAllEntitiesWithParam("JobsDb_Users_GetByEmail", user.Email).FirstOrDefault();
...
try {
var tryLogin = WebSecurity.Login(users.Username, user.Password, true);
if (tryLogin == WebSecurity.MembershipLoginStatus.Failure)
{
var httpCookie = Request.Cookies["lang"];
if (httpCookie != null && httpCookie.Value == "en") {
ViewBag.Error = "Your password is incorrect.";
new SeoHelper().ReturnSeoTags(this, "Login");
}
return View(user);
}
...
} catch {
...
}
}
inside WebSecurity
public static MembershipLoginStatus Login(string username, string password, bool rememberMe) {
if (Membership.ValidateUser(username, password)) {
FormsAuthentication.SetAuthCookie(username, rememberMe);
return MembershipLoginStatus.Success;
} else {
return MembershipLoginStatus.Failure;
}
}
inside Membership
public override bool ValidateUser(string username, string password) {
if (string.IsNullOrEmpty(username)) {
return false;
}
if (string.IsNullOrEmpty(password)) {
return false;
}
User user = _userRepository.GetAll().FirstOrDefault(usr => usr.Username == username);
if (user == null) {
return false;
}
if (!user.IsApproved.Value) {
return false;
}
if (user.IsLockedOut.Value) {
return false;
}
String hashedPassword = user.Password;
Boolean verificationSucceeded = (hashedPassword != null && Crypto.VerifyHashedPassword(hashedPassword, password));
if (verificationSucceeded) { //here is I have false if try to login using password from forget form
user.PasswordFailuresSinceLastSuccess = 0;
user.LastLoginDate = DateTime.UtcNow;
user.LastActivityDate = DateTime.UtcNow;
} else {
int failures = user.PasswordFailuresSinceLastSuccess.Value;
if (failures < MaxInvalidPasswordAttempts) {
user.PasswordFailuresSinceLastSuccess += 1;
user.LastPasswordFailureDate = DateTime.UtcNow;
} else if (failures >= MaxInvalidPasswordAttempts) {
user.LastPasswordFailureDate = DateTime.UtcNow;
user.LastLockoutDate = DateTime.UtcNow;
user.IsLockedOut = true;
}
}
_userRepository.SaveChanges();
if (verificationSucceeded) {
return true;
}
return false;
}
First step is to open up your database and verify that the new password was actually persisted. If it has, the most likely cause is that your repository is working with stale (cached) data.
If you're using Entity Framework, this happens because the framework will, by default, cache the state of the database at the time the DbContext is created, so it is retaining your original password. You can verify this by logging in with the original password.
I am not sure but following code does not look right to me:
User user = _userRepo.GetUserByEmail(userModel.Email);
if (user == null) {
ViewBag.Error = Resources.Account.userEmailNotExist;
return View(userModel);
}
String newHashedPassword = Crypto.HashPassword(result);
user.Password = newHashedPassword;
user.LastPasswordChangedDate = DateTime.UtcNow;
_userRepo.SaveChanges();
You fetched the user from repository, make changes to user object in memory and then called SaveChanges() on the repository. Does that work in your world? How does _userRepo.SaveChanges(); knows which object has changed. Do you see correct hashed value in DB after the call? What value you see in ValidateUser() method for password? Is the hashing algorithm consistent both while generating hashed password and while verifying?
I could be wrong, if that's the case it will be good if you share little bit more of analysis around the question I asked above.