asp.net mvc form authenticate lose cookie session - asp.net-mvc

asp.net mvc project when publish, it always lose session after 15-20 minutes.
my global.asax
enter code protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder());
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
if (authTicket != null && !authTicket.Expired)
{
var roles = authTicket.UserData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
}
}
}
Login Method :
//clear any other tickets that are already in the response
Response.Cookies.Clear();
//set the new expiry date - to thirty days from now
DateTime expiryDate = DateTime.Now.AddDays(30);
//create a new forms auth ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, login.EmailID, DateTime.Now, expiryDate, true, "Kullanici Bilgisi");
//encrypt the ticket
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
//create a new authentication cookie - and set its expiration date
HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
authenticationCookie.Expires = ticket.Expiration;
authenticationCookie.HttpOnly = true;
//add the cookie to the response.
Response.Cookies.Add(authenticationCookie);
Please help me. Im control on google developer tools. I see timeout 2018 but session is always losing redirect to login page.
Web Config:
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/user/login" slidingExpiration="true"></forms>
</authentication>

Related

How to maintain a Id value throughout my Asp.net MVC application session management

How to maintain a Id value throughout my Asp.net MVC application after login -- Persist ID throughout ASP.NET MVC application?
I tried using session variable like this in login controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LoginPage(UserLogin login)
{
else if (string.Compare(CryptoCode.Hash(login.Password), v.PPassword) == 0)
{
int timeout = login.RememberMe ? 60 : 60; // 525600 min = 1 year
var ticket = new FormsAuthenticationTicket(login.EmailID, login.RememberMe, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = DateTime.Now.AddMinutes(timeout);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
var profile = db.Profile.Where(x => x.UserLoginId == v.UserLoginId).FirstOrDefault();
Session["PId"] = profile.PId;
if (Url.IsLocalUrl(login.ReturnUrl))
{
return Redirect(login.ReturnUrl);
}
else
{
return Redirect("/ProfilePage/fileupload/index");
}
}
In my Another Controller top level
public ActionResult MainPage()
{
if (Session["PId"] != null)
{
Int64 pid = (Int64)System.Web.HttpContext.Current.Session["PId"];
......
......
}
else
{
return View("~/Registration/Registration/loginpage");
}
}
In web.config file
<authentication mode="Forms">
<forms cookieless="UseCookies" loginUrl="~/Registration/loginpage" timeout="60" slidingExpiration="true"></forms>
</authentication>
<sessionState mode="InProc" timeout="60"></sessionState>
when i close browser the session value getting null but my session login is active, so i get null reference exception or pid null.
In my application i have many controllers that have many action methods. i am not interested to check if condition session value in every action method.
How to maintain a session value after browser close and reopen in given timeout in session (like 20 min)?

How to get forms authentication ticket to respecting cookie expiration date

I am having an issue where users of my website login sessions are expiring way before it should.
Here is my login method”
public ActionResult Login(LoginModel model, string returnUrl)
{
var mcookie = new MyCompanyCookie();
if (ModelState.IsValid)
{
using (var myRepo = new MyCompanyRepositry())
{
var passwordHash = MyCompany.Web.Portal.Helpers.Security.CreatePasswordHash(model.Password);
var userAccount = myRepo.GetMyCompanyUser(model.UserName,model.PartnerAccessCode);
if(userAccount != null && userAccount.Password == passwordHash && userAccount.PartnerAccessCode == model.PartnerAccessCode.ToUpper())
{
mcookie.GetMMformsauthentication(userAccount, model.RememberMe);
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name,access code or password provided is incorrect.");
}
}
And forms authentication ticket:
public void GetMMformsauthentication(UserAccount useraccount, bool createPersistentCookie)
{
const string UnknownUsername = "anonymous";
// Composing UserData to be stored in the auth cookie
var userCookieData = new MarvMentUserCookieData()
{
UserId = useraccount.UserID,
Password = useraccount.Password,
PartnerAccessCode = useraccount.PartnerAccessCode
};
var ticket = new FormsAuthenticationTicket(1, string.IsNullOrEmpty(useraccount.UserID) ? UnknownUsername : useraccount.UserID, DateTime.Now,
DateTime.Now.AddDays(100), createPersistentCookie, userCookieData.ToString(), FormsAuthentication.FormsCookiePath);
var hashedCookie = FormsAuthentication.Encrypt(ticket);
HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashedCookie); // Hashed ticket
authCookie.HttpOnly = true;
authCookie.Expires = ticket.Expiration;
authCookie.Path = ticket.CookiePath;
authCookie.Secure = false;
HttpContext.Current.Response.SetCookie(authCookie);
}
}
And expiration settings inmy Web.config
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Here you can see that the forms expiration settings is set 2880 minutes however users are beign logged out after around 5-10 minutes.
The cookie is set to expire in 100 days
Does anyone have and idea what may be causing this issue?
It looks issue is not with session in authentication tag. Just check what happens if cookies stuff is commented... If Session retained for more time, then focus on cookie stuff.

Cross domain session asp mvc in IE and old browsers

Lets say that you have websites http://simple.com and a lot of subdomain, for example: http://first.simple.com, http://second.simple.com, http://last.simple.com.
Lets say that a user goes to last.simple.com and they get authenticated through the normal ASP .NET membership provider.
Then, from that site, they get sent to (redirection, linked, whatever works) site http://last.simple.com, and the intent of site http://first.simple.com was to pass that user to the other site as the status of isAuthenticated, so that the site http://last.simple.com does not ask for the credentials of said user again.
This worked in Chrome, Mozila, Opera(last versions), Safari, but don't worked in IE(all versions) and Opera( < v12.01).
Scheme:
User, address(first.simple.com) -> post query to server, json answer,
if auth - redirect. May be problem in json(need use 'jsonp')?
web.config
<system.web>
<authentication mode="Forms">
<forms name=".ASPXAUTH" protection="All" domain=".simple.com" enableCrossAppRedirects="true" />
</authentication>
</system.web>
SessionService
public void Authenticate(string username)
{
FormsAuthentication.SetAuthCookie(username, false);
var cookie = FormsAuthentication.GetAuthCookie(username, false);
cookie.HttpOnly = true;
cookie.Path = "/";
cookie.Domain = domain;
this.context.Response.AppendCookie(cookie);
}
Global.asax
protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
const string aspSessionid = "ASP.NET_SessionId";
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
var cookie = Context.Request.Cookies[aspSessionid];
if (cookie != null && Context.Session != null && !string.IsNullOrEmpty(Session.SessionID))
{
Response.Cookies.Add(new HttpCookie(aspSessionid, Session.SessionID) { Domain = domain, Path = "/", Expires = DateTime.Now.AddDays(30) });
}
}
}

asp.net mvc authentication cookie issue

I'm trying to implement a "remember me" feature using ASP.NET MVC. It uses a customized authentication process as defined below.
Web.config:
<authentication mode="Forms">
<forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
</authentication>
Code to persist cookie:
public void SignIn(string userName, bool createPersistentCookie) {
int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
Code to retrieve cookie:
if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
}
The current code checks for Session for authentication. I'd like to add the ability to get the userName from cookie as well. I have 2 questions:
What do I need to do in order to retrieve the cookie?
How do I decrypt the cookie to obtain the userName?
To get the cookie:
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
Decrypt it with:
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData

Asp.Net MVC FormsAuthenticationTicket

Im setting FormsAuthenticationTicket in the Logon method to manually create an authentication cookie. How do I validate that authentication cookie and assign it the Current.User object. Is it done in the Global.asax page?
Logon code:
FormsAuthenticationTicket Authticket = new
FormsAuthenticationTicket(1,
model.UserName,
DateTime.Now,
DateTime.Now.AddYears(1),
true,
"",
FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(Authticket);
HttpCookie Authcookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
if (Authticket.IsPersistent) Authcookie.Expires = Authticket.Expiration;
Response.Cookies.Add(Authcookie);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
How do i read this cookie and validate the user?
my code so far in the global.asax file:
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
FormsIdentity id = new FormsIdentity(authTicket);
GenericPrincipal principal = new GenericPrincipal(id,null);
Context.User = principal;
}
I moved this type of code into a base controller. There is a method called "OnAuthorization" in the Controller class that can be overridden.
It's been a little while, but I believe all requests (images, css... etc) where going through the OnAuthorization method in the Global.asax. By pushing the authorization down to the controller you are only getting the request to your controller/actions

Resources