Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net identity - Reset cookies and session on iis recycle (restart)

I have implemented asp.net mvc with asp.net identity authentication.

I have used cookie based authentication. After restart the IIS/stop and start the IIS for the my site, when i open my website, the user is automatically login to the system.

The user cookie is not cleared and still valid for the user. How to force the user to log out after restart the iis?

I have used default sample from the website. http://www.nuget.org/packages/Microsoft.AspNet.Identity.Samples

enter image description here

app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
like image 651
Jeeva J Avatar asked Sep 23 '16 11:09

Jeeva J


2 Answers

Cookies are not meant to be invalidated when IIS is restarted - this is not how HTTP protocol works. Cookies being invalidated on IIS restart can lead to some strange behaviour in production - IIS can be plunged any time, or there could be load-balancer that uses a few IIS servers to serve the requests - what would happen if one of the servers restarts?

Anyway, you can kill all the cookies for all the users by mass-updating ApplicationUser.SecurityStamp in the database. And in Startup.Auth.cs set validateInterval: TimeSpan.FromMinutes(2) - this will invalidate all the cookies within 2 minutes of the SecurityStamp update. Value lower than this is not recommended - this will cause performance issues.

like image 196
trailmax Avatar answered Oct 13 '22 09:10

trailmax


For this, I have done a trick.

We are using session to store the dynamic variables and asp.net identity for authentication in ASP.NET MVC.

  1. Each request I have interrupted.
  2. I have checked like whether asp.net identity is valid and session is invalid.
  3. If session is invalid, then make the cookies invalid and navigate the user to specific page.

    public class SessionHandler : ActionFilterAttribute
    {
        private ApplicationUserManager _userManager;
        private IAuthenticationManager AuthenticationManager
        {
            get
            {
                return HttpContext.Current.GetOwinContext().Authentication;
            }
        }
        public ApplicationUserManager UserManager
        {
            get
            {
                return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
            }
            private set
            {
                _userManager = value;
            }
        }
        public IIdentity UserIdentity
        {
            get { return System.Web.HttpContext.Current.User.Identity; }
        }
    
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
    
            if (!string.IsNullOrWhiteSpace(UserIdentity.GetUserId()))
            {
                if (System.Web.HttpContext.Current.Session["Username"] == null)
                {
                    AuthenticationManager.SignOut();
                    filterContext.Result = new RedirectToRouteResult(
                                  new RouteValueDictionary
                                  {
                                       { "action", "Index" },
                                       { "controller", "Home" }
                                  });
                }
            }
        }
    }
    

In Global.asax file

Add the following code

GlobalFilters.Filters.Add(new SessionHandler());
like image 1
Jeeva J Avatar answered Oct 13 '22 09:10

Jeeva J