Skip to navigation Skip to content
Simon Technology Blog
  • Architecture
  • Cloud
  • Database
  • Develop
  • Hardware
  • Industry
  • Language
  • Mobile
  • Opensource
  • OS
  • Web
Main Navigation

.NET – FormsAuthenticationalTicket: How to keep the user log in after the browser is closed?

August 22, 2021By Simo Browser

I use FormsAuthenticationTicket to log users in this way:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel loginView)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(loginView.Email, loginView.Password))
{
var user = (CustomMembershipUser)Membership.GetUser(loginView.Email, false);
if (user != null)
{
CustomPrincipalSerializeModel userSerializeModel = new CustomPrincipalSerializeModel( )
{
ID = user.ID,
FirstName = user.FirstName,
LastName = user.LastName,
RoleName = user.Roles.Select(r = > r.RoleName).ToList()
};

string userData = JsonConvert.SerializeObject(userSerializeModel);
DateTime expirationDate = loginView.KeepMeLoggedIn? DateTime.Now.AddMonths(12): DateTime.Now.AddMinutes(15);
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, expirationDate, false, userData);

HttpCookie faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(faCookie);
}

return RedirectToAction("Index", "Home");
}
}

ModelState.AddModelError("", "Login Error");
< br /> return View("Login");
}

But even if I set loginView.KeepMeLoggedIn to true (should stay logged in for 1 year), when I close the browser and reopen the website , The user will be logged out.

How do I keep logged in when I close the browser?

First, you need to set the fifth parameter of the FormsAuthenticationTicket constructor’isPersistent’ to true.

Then I will add the change code to this:

var faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket)) ;
if (authTicket.IsPersistent)
{
faCookie.Expires = authTicket.Expiration;
}
Response.Cookies.Add(faCookie);

If you also want to respect the content configured in web.config, you can add this additional code (optional):

var faCookie = new HttpCookie(FormsAuthentication. FormsCookieName, FormsAuthentication.Encrypt(authTicket));
faCookie.Path = FormsAuthentication.FormsCookiePath;

if (FormsAuthentication.RequireSSL)
{
faCookie.Secure = true ;
}

if (FormsAuthentication.CookieDomain != null)
{
faCookie.Domain = FormsAuthentication.CookieDomain;
}
. ..

I use FormsAuthenticationTicket to record users in this way:

[HttpPost]
[ValidateAntiForgeryToken]
pu blic ActionResult Login(LoginViewModel loginView)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(loginView.Email, loginView.Password))
{
var user = (CustomMembershipUser)Membership.GetUser(loginView.Email, false);
if (user != null)
{
CustomPrincipalSerializeModel userSerializeModel = new CustomPrincipalSerializeModel()< br /> {
ID = user.ID,
FirstName = user.FirstName,
LastName = user.LastName,
RoleName = user.Roles.Select(r => r .RoleName).ToList()
};

string userData = JsonConvert.SerializeObject(userSerializeModel);
DateTime expirationDate = loginView.KeepMeLoggedIn? DateTime.Now.AddMonths(12) : DateTime.Now.AddMinutes(15);
FormsAuthenticationTicket authTi cket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, expirationDate, false, userData);

HttpCookie faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(faCookie);
}

return RedirectToAction("Index", "Home");
}
}

ModelState.AddModelError("", "Login Error");

return View("Login");
}

But even if I log inView .KeepMeLoggedIn is set to true (should remain logged in for 1 year), when I close the browser and reopen the website, the user will be logged out.

When I close the browser, how do I keep logged in?

First, you need to set the fifth parameter of the FormsAuthenticationTicket constructor’isPersistent’ to true.

Then I Will add the change code to this:

var faCookie = new HttpCookie("CookieFA", FormsAuthentication.Encrypt(authTicket));
if (authTicket.IsPersistent)< br />{
faCookie.Expires = authTicket.Expiration;
}
Response.Cookies.Add(faCookie);

If you also want to respect web.config You can add this extra code (optional) to the content configured in the

var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
faCookie.Path = FormsAuthentication.FormsCookiePath;

if (FormsAuthentication.RequireSSL)
{
faCookie.Secure = true;
}

if (FormsAuthentication.CookieDomain != null)
{
faCookie.Domain = FormsAuthentication.CookieDomain;
}
...

browser, close, FormsauthenticationalTicket, hold, How, login, status, user

Post navigation

129 mysql data type (important)
What is node.js?

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 452 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment Cancel reply

Your email address will not be published.

Recent Posts
  • Sencha-Touch-2 – Sencha Touch 2, Nested XML Analysis NodeValue
  • Add a separation line and format XML content
  • Is there a norm of simplified XML subsets?
  • Look at it when you write React
  • ReactJS – Present React Redux React-Router App to add the server to the Firebase hosted by the Firebase
Categories
  • Android
  • Apache
  • Apache Kafka
  • Asp
  • Auto-Test
  • Automated Build
  • Aws
  • Bitcoin
  • Browser
  • C & C++
  • C#
  • Centos
  • Cgi
  • Character
  • Cloud Service
  • Cocos2dx
  • Cordova
  • CSS
  • Data Structure
  • Delphi
  • Design Pattern
  • Dojo
  • Dubbo
  • ELK
  • Flex
  • football
  • Game
  • Hadoop
  • Hibernate
  • HTML
  • Hybrid
  • Intel
  • IOS
  • Ipad
  • iPhone
  • Java
  • Javascript
  • Jetty
  • JQuery
  • Jsp
  • Linux
  • Load Balance
  • Lua
  • Macbook
  • Macos
  • Mathematics
  • Micro Services
  • Monitoring
  • Motherboard
  • Mysql
  • Network Hardware
  • Network Marketing
  • Nginx
  • NodeJs
  • Nosql
  • Oracle
  • Os Theory
  • Performance
  • PHP
  • Postgresql
  • Power Designer
  • React
  • Redis
  • Regexp
  • Rom
  • Rss
  • Ruby
  • Search Engines
  • Shell Script
  • Silicon Valley
  • Silverlight
  • Software Design
  • Spring
  • Sql
  • Sqlite
  • Sqlserver
  • Storage
  • Storm
  • Surface
  • SVN
  • Swift
  • System Architecture
  • Tablet
  • Uncategorized
  • Unix
  • Visual Basic
  • Visual Studio
  • Web Crawler
  • WebService
  • Windows
  • Wireless
  • XML
  • ZooKeeper
Archives
  • October 2021
  • September 2021
  • August 2021
  • May 2021
  • April 2021
  • September 2020
  • September 2019
  • August 2019
  • June 2019
  • May 2019
  • April 2019
  • March 2019
© Simon Technology Blog 2025 • ThemeCountry Powered by WordPress