How to get and set values into cookie in ASP.NET MVC - c#

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.

Related

Authorize issue in MVC - database used flat file

I am new to MVC. I am facing below problem.
I wrote all logic in model.In Web.config I mention path of file (No Connection string).
I am adding [Authorize] attribute. After login, it is navigating to Home page. When I navigate gift create page again redirect to login page (Recursive).
FYI: Temporarily I am using session variable to solve problem.
This is my code
[HttpPost]
[ActionName("Create")]
[Authorize]
public ActionResult CreateGift(GiftModel gif)
{
if (Session["UserType"] != null)
{
if (Session["UserType"].ToString() == "1")
return RedirectToAction("Index", "home");
}
else
{
return RedirectToAction("Login", "User");
}
string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
if (ModelState.IsValid)
{
Gift InsertCoupon = new Gift(path);
InsertCoupon.InsertGift(gif);
return RedirectToAction("GiftList");
}
return View();
}
In Web.config
<add key="Path" value="D:\"/>
Login Page
public ActionResult Login(LoginModel user)
{
string path = System.Configuration.ConfigurationManager.AppSettings["Path"];
if(ModelState.IsValid)
{
Users LoginUser = new Users(path);
UserModel uM = new UserModel();
uM.Password = user.Password;
uM.User_Email_ID = user.User_Email_ID;
uM.Name = user.Name;
string res = LoginUser.LoginUser(uM);
uM = LoginUser.GetUserFrom_Email(user.User_Email_ID);
if (res != "")
ViewBag.Msg = res;
else
{
Session["username"] = uM.Name;
Session["E_Mail"] = uM.User_Email_ID;
Session["UserType"] = uM.User_Type;
if (uM.User_Type == 0)
return RedirectToAction("AdminHome", "Admin");
else
return RedirectToAction("Index", "Home");
}
}
return View();
}

asp.net mvc 4 login cookies not working

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);
}

FormAuthentication .ASPXAUTH cookie showing null after few moments in ASP.NET MVC

I have implemented FormAuthentication in asp.net mvc 5 and create FormsAuthenticationticket on LogIn and it creates successfully but after few moments that cookie is showing in browser but in application it's getting null.
Please help to solve this issue.
Any help will be appreciated Thanks
LOGIN FORM
public ActionResult Login([Bind(Include = "Username, Password")] LoginModel loginModel, string ReturnUrl)
{
if (ModelState.IsValid)
{
Egov_Users eGov_Users = db.Egov_Users
.Where(p => p.UserType.Type != "O" && p.UserName == loginModel.Username)
.FirstOrDefault();
if (eGov_Users == null)
{
ModelState.AddModelError("", "Invalid username");
return View();
}
else
{
if (eGov_Users.Password != loginModel.Password)
{
ModelState.AddModelError("", "Invalid Password");
return View();
}
var loginDetail = new LoginDetails();
var serializer = new JavaScriptSerializer();
loginDetail.userID = eGov_Users.UserId;
loginDetail.username = eGov_Users.UserName;
loginDetail.firstName = eGov_Users.FirstName;
loginDetail.lastName = eGov_Users.LastName;
var userData = SerializeUserInfoInternal(loginDetail);
FormsAuthentication.SetAuthCookie(loginDetail.username, false);
var cookie = FormsAuthentication.GetAuthCookie(
FormsAuthentication.FormsCookieName, false);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var durationInHours = 8;
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
ticket.Version,
loginDetail.username,
DateTime.Now,
DateTime.Now.AddHours(durationInHours),
true,
userData);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(newTicket);
cookie.Value = encTicket;
Response.Cookies.Add(cookie);
int cookieSize = System.Text.UTF8Encoding.UTF8.GetByteCount(cookie.Values.ToString());
Session["CookieSize"] = cookieSize;
if (string.IsNullOrEmpty(ReturnUrl))
{
return RedirectToAction("Index", "Users");
}
}
}
return RedirectToAction("Login", "Login");
}
GLOBAL ASAX
protected void Application_PostAuthenticateRequest()
{
var ticket = GetTicketFromCurrentCookie();
if (ticket == null)
{
Global.WriteLog("Application_PostAuthenticateRequest", "ticket becomes null");
return;
}
var user = DeserializeUserInfoInternal(ticket.Name, ticket.UserData);
if (user == null)
{
return;
}
var principal = new AppUserPrincipal(user);
HttpContext.Current.User = principal;
}
private static FormsAuthenticationTicket GetTicketFromCurrentCookie()
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null)
{
Global.WriteLog("GetTicketFromCurrentCookie", "Cookie becomes null");
return null;
}
var ticket = FormsAuthentication.Decrypt(cookie.Value);
return ticket;
}
static LoginDetails DeserializeUserInfoInternal(string name, string userData)
{
var deserialize = new JavaScriptSerializer();
var loginDetails = deserialize.Deserialize<LoginDetails>(userData);
return loginDetails;
}
use below code to get the cookie value
HttpContext.Current.Request.Cookies.Get(".ASPXAUTH");

Asp.Net MVC Culture Cookie Changes But Not UI Language Until Second Refresh

In my Asp.Net MVC application, the users come from another system with a URL that contains their own UserId. In the initial request of the users, after the authentication process, the user's language option is synchronized to the corresponding cookie value.
[HttpPost]
[AllowAnonymous]
public JsonResult Login(Guid userId, UserType userType)
{
try
{
IAccount account = null;
if (userType == UserType.SystemUser)
account = _accountService.CheckSystemUser(userId);
if (userType == UserType.Employee)
account = _accountService.CheckEmployee(userId);
if (account == null) throw new Exception(ErrorMessages.UserNotFound);
var roles = account.Roles.ToArray();
var principalModel = new CustomPrincipalViewModel
{
UserId = account.UserId.ToString(),
FullName = account.FullName,
Roles = roles,
Language = account.Language
};
var userData = JsonConvert.SerializeObject(principalModel);
var ticket = new FormsAuthenticationTicket(1, principalModel.FullName, DateTime.Now,
DateTime.Now.AddMinutes(30), false, userData);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var requestCookie =Request.Cookies[FormsAuthentication.FormsCookieName];
if (requestCookie != null) requestCookie.Expires = DateTime.Now.AddDays(-1);
var responseCookie =Response.Cookies[FormsAuthentication.FormsCookieName];
if(responseCookie != null) responseCookie.Expires = DateTime.Now.AddDays(-1);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
SetCulture(account.Language.CultureCode);
return Json(new {isSuccess = true, userFullName = account.FullName});
}
catch (BusinessExceptions.CannotConnectToCrmServiceException ex)
{
ElmahManager.Log(ex);
return Json(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
}
catch (Exception exception)
{
ElmahManager.Log(exception);
return Json(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
}
}
private void SetCulture(string culture)
{
culture = CultureHelper.GetImplementedCulture(culture);
var requestCookie =Request.Cookies["_culture"];
if (requestCookie != null) requestCookie.Expires = DateTime.Now.AddDays(-1);
var cultureCookie = Request.Cookies["_culture"];
if (cultureCookie == null)
{
cultureCookie = new HttpCookie("_culture")
{
Value = culture,
Expires = DateTime.Now.AddYears(1)
};
}
else
{
cultureCookie.Value = culture;
cultureCookie.Expires = DateTime.Now.AddYears(1);
}
Response.Cookies.Add(cultureCookie);
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
After this process, when I change the language selection of the user from the database and refresh the page, the page language does not change. In the meantime, when I check the cookie value, I see that it is the same as the current language value, but the page language does not change until the page is refreshed a second time.
You have to change
public JsonResult Login(Guid userId, UserType userType)
to
public ActionResult Login(Guid userId, UserType userType)
and return View or Redirect.
[HttpPost]
[AllowAnonymous]
public ActionResult Login(Guid userId, UserType userType)
{
try{
//Your logic
return View(new {isSuccess = true, userFullName = account.FullName});
}
catch (BusinessExceptions.CannotConnectToCrmServiceException ex)
{
ElmahManager.Log(ex);
return View(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
}
catch (Exception exception)
{
ElmahManager.Log(exception);
return View(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
}
}

Forget password form in asp.net mvc 4

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.

Categories

Resources