Here is my get:
protected string Identifier
{
get
{
HttpCookie cookie = Request.Cookies[IDENTIFIER_COOKIE];
if (cookie != null)
{
return cookie.Value;
}
else
{
cookie = new HttpCookie(IDENTIFIER_COOKIE);
cookie.Value = Guid.NewGuid().ToString();
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
return cookie.Value;
}
}
}
When running my project locally, the cookie's expiry date is set as expected
But when I run it live, the cookie's expiry date is When the browsing session ends.
What am I doing wrong?
The problem was that my page was served on HTTPS. I had to specifiy cookie.Secure = true for the expiry date to be set.
Before doing anything else, I suggest that you clear your cache and cookies.
protected string Identifier
{
get
{
HttpCookie cookie = Request.Cookies[IDENTIFIER_COOKIE];
if (!cookie)
{
cookie = new HttpCookie(IDENTIFIER_COOKIE);
cookie.Value = Guid.NewGuid().ToString();
}Cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Set(cookie);
return cookie.Value
}
}
Related
In my Asp.Net MVC application users are coming from another system and I'm logging them in like below.
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 cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Add(cookie);
SetCulture(account.Language.CultureCode);
return Json(new { isSuccess = true, userFullName = account.FullName });
And setting current culture like this with SetCulture method.
private void SetCulture(string culture)
{
culture = CultureHelper.GetImplementedCulture(culture);
var cookie = Request.Cookies["_culture"];
if (cookie != null)
{
cookie.Value = culture;
cookie.Expires = DateTime.Now.AddYears(1);
}
else
{
cookie = new HttpCookie("_culture")
{
Value = culture,
Expires = DateTime.Now.AddYears(1)
};
}
Response.Cookies.Add(cookie);
}
And my view pages I'm setting text values from Resource files like below.
<span class="pageButton"> #Global.Cancel </span>
But when I change user language from other system and log in again to my system, all texts are still in previous language. After I refresh my page with ctrl+F5 everything looks in true language.
Is there a way to force to load page texts in new language without clearing cache manually ?
The problem in cookie var cookie = Request.Cookies["_culture"];, still keep old value, clean it when you logOff or when you try to log-In again
And you can use also Thread.CurrentThread to set culture
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
I have an issue with ASP.NET cookies being lost between requests.
I have an ASCX control which has multiple filtering checkboxes. I can check/uncheck these checkboxes and then I click a . In this applyFilters method, I am setting cookies based on whether the checkboxes are checked/unchecked. The code that does this is :
public void setFilterCookie(string name, string val)
{
if (!String.IsNullOrEmpty(val) && (val != null && !val.Equals("-1")))
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
HttpCookie cookie = new HttpCookie(name, val);
cookie.Expires = DateTime.Now.AddDays(5);
response.Cookies.Add(cookie);
}
else
{
if (request.Cookies[name] != null)
{
HttpCookie myCookie = new HttpCookie(name);
myCookie.Expires = DateTime.Now.AddDays(-2d);
response.Cookies.Add(myCookie);
request.Cookies.Remove(name);
}
}
}
After the cookies are set, I want to databind a grid from the parent container of the control. In this databind method I am reading the cookies using the following method :
public string getCookie(string cookieName)
{
if (isNotNullOrEmpty(cookieName))
return request.Cookies[cookieName].Value.ToString().Trim();
else
return null;
}
The problem is that when I am setting the cookies, I can see the values being set (e.g. response.Cookies["Domain"] = "5") but when I am reading them the value is string empty.
Can somebody tell me what is wrong?
Thank you
You shouldn't be removing request cookies and adding response cookies with the same name multiple times. This should work.
public void setFilterCookie(string name, string val)
{
var cookieValue = string.Empty;
var expires = 0;
if (!string.IsNullOrWhiteSpace(val) && !val.Equals("-1"))
{
cookieValue = val;
expires = 5;
}
else
{
expires = -2;
}
var cookie = new HttpCookie(name, cookieValue) {Expires = DateTime.Now.AddDays(expires)};
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
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.
Using FormsAuthentication, I am creating a FormsAuthenticationTicket, encrypting, adding this to a cookie using Response.Cookies.Add(authCookie). I then do a redirect using Response.Redirect to the original page that was requested. There is code in the Global.asax in the Application_AuthenticateRequest method that looks to retrieve the cookie - HttpCookie authCookie = Context.Request.Cookies[cookieName]. For some reason, however, when it hits the Global.asax code after the redirect is called, there are no cookies in the collection. At this point, I am a bit stumped as to why it is losing the cookie from the collection. Any thoughts as to why this would happen? Right now, I am just working within localhost.
Login Page Code:
string adPath = "LDAP://ldapserveraddress";
LdapAuthentication adAuth = new LdapAuthentication(adPath);
try
{
if (true == adAuth.IsAuthenticated("ES", txtUsername.Text, txtPassword.Text))
{
string groups = adAuth.GetGroups();
//Create the ticket, and add the groups.
bool isCookiePersistent = chkPersist.Checked;
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
txtUsername.Text, DateTime.Now, DateTime.Now.AddMinutes(60), isCookiePersistent, 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);
string redirect = FormsAuthentication.GetRedirectUrl(txtUsername.Text, false);
//You can redirect now.
Response.Redirect(redirect,false);
}
else
{
errorLabel.Text = "Authentication did not succeed. Check user name and password.";
}
}
catch (Exception ex)
{
errorLabel.Text = "Error authenticating. " + ex.Message;
}
}
Global.asax Code (Application_AuthenticateRequest):
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = Context.Request.Cookies[cookieName];
if (null == authCookie)
{
//There is no authentication cookie.
return;
}
FormsAuthenticationTicket authTicket = null;
try
{
authTicket = FormsAuthentication.Decrypt(authCookie.Value);
}
catch (Exception ex)
{
//Write the exception to the Event Log.
return;
}
if (null == authTicket)
{
//Cookie failed to decrypt.
return;
}
//When the ticket was created, the UserData property was assigned a
//pipe-delimited string of group names.
string[] groups = authTicket.UserData.Split(new char[] { '|' });
//Create an Identity.
GenericIdentity id = new GenericIdentity(authTicket.Name, "LdapAuthentication");
//This principal flows throughout the request.
GenericPrincipal principal = new GenericPrincipal(id, groups);
Context.User = principal;
}`
I was able to resolve my issue by adjusting the data that was being stored in the userData of the FormsAuthenticationTicket. It appears as though the amount of data that I was trying to insert exceeded a maximum. Once I removed, everything works as expected.
I want to make login and logOut functions in mvc4. In login func, if login cookie exist and not empty, user is in signIn mode, else redirect to login page.
In logOut func, all cookies and sessions clear and redirect to login func, but in login func login cookie exist!
Login:
public ActionResult Login()
{
if (Request.Cookies["login"] != null)
{
string login = Request.Cookies["login"].Value.ToString();
if (login != string.Empty)
{
//Get from service
Service srv = new Service();
UserItem userItem = srv.getUserItem(login);
srv.Close();
Session.Timeout = 30;
Session["login "] = login;
Session["userId"] = userItem.No;
Session["firstName"] = userItem.FirstName;
Session["lastName"] = userItem.LastName;
string loginName = userItem.LoginName;
FormsAuthentication.SetAuthCookie(loginName, false);
return Redirect(“Index”);
}
else
{
Return redirect("http://mySite/SignIn.aspx");
}
}
else
{
Return redirect("http://mySite/SignIn.aspx");
}
}
LogOut:
public ActionResult LogOut()
{
string login = Session["login"].ToString();
Request.Cookies["login"].Value = "";
Response.Cookies["login"].Value = "";
FormsAuthentication.SignOut();
HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
c.Expires = DateTime.Now.AddDays(-1);
Session.Clear();
Request.Cookies.Clear();
Response.Cookies.Clear();
//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)));
//Session.Abandon();
//// clear authentication cookie
//HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
//cookie1.Expires = DateTime.Now.AddYears(-1);
//Response.Cookies.Add(cookie1);
//// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
//HttpCookie cookie2 = new HttpCookie("ASP.NET_SessionId", "");
//cookie2.Expires = DateTime.Now.AddYears(-1);
//Response.Cookies.Add(cookie2);
//FormsAuthentication.RedirectToLoginPage();
return RedirectToAction("Login", "Usr");
}
Web.config:
<authentication mode="Forms">
<forms loginUrl="~/Usr/Login" timeout="30" />
</authentication>
I am trying comment codes, even comment this line:
FormsAuthentication.SignOut();
Even I set the cookie value to "", but in login page this cookie have old value!
And trying several ways to clear cookie like set expire to one day later. But…
Thanks
You're changing the value of the cookie, but you're not adding it to the response again!
FormsAuthentication.SignOut();
HttpCookie c = Request.Cookies[FormsAuthentication.FormsCookieName];
c.Expires = DateTime.Now.AddDays(-1);
// Update the amended cookie!
Response.Cookies.Set(c)
Session.Clear();
/* Get rid of this, it will break the above by clearing
* the cookie collection that you've just updated. */
// Request.Cookies.Clear();
// Response.Cookies.Clear();
There is a much easier way to determine if the user is authenticated, as per this post
How to check if user is authorized inside Action
After you have called the FormsAuthentication.SetAuthCookie(), you can call User.Identity.IsAuthenticated. No need to set your own cookies.
If you do it like this, the FormsAuthentication.SignOut() will destroy the correct cookie
Thank you AndreyMaybe, Ant P
This code work:
Response.Cookies.Clear();
FormsAuthentication.SignOut();
HttpCookie c = new HttpCookie("login");
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
Session.Clear();