Logout User From all Browser When Password is changed
Asked Answered
J

6

21

I have a Reset Password page: enter image description here

When the user fills the details and clicks the Reset Password button. The following controller is called:

public ActionResult ResetPassword(ResetPassword model)
{
    ...
    return RedirectToAction("Logout");
}

When the user changes their password, they get Logged Out from the browser. However, if they are logged into another browser at the same time they remain logged in on the other browser.

I want to log out the user from all browsers they are logged into when they change their password.

Jackhammer answered 5/2, 2016 at 9:53 Comment(0)
T
8

So I got home and decided to put together some code. Show me the code !!!

I would use a handler so the verification is always done when the user first access the application and it is done at one place for every action method access.

The idea is when the user reset their password, the application records the user has reset their password and have not logged in for the first time and sign out the user.

user.HasResetPassword = true;
user.IsFirstLoginAfterPasswordReset = false;

When the user signs in, the application verifies if the user had previously reset their password and is now signing in for the first time. If these statements are valid the application updates its records to say you have not reset your password and you are not signing in for the first time.

Step 1

Add two properties to ApplicationUser model

enter image description here

Step 2

Add a class AuthHandler.cs in Models folder with the implementation below. At this stage you verify if the user has reset their password and has not logged in for the first time since the password was reset. If this is true, redirect the user to the login.

enter image description here

Step 3

In RouteConfig.cs call the AuthHandler so that it is invoked for each incoming http request to your application. enter image description here

Step 4

In ResetPassword method add implementation as below. At this step when a user has reset their password update the properties to say , they have reset their password and have not logged in for the first time. Notice the user is also signed out explicitly when they reset their password.

enter image description here

Step 5

In Login method add the implementation below. At this step if a user logins in successfully, verify their password was reset and they has logged for the first time is false. If all the conditions are true, update the properties in the database, so the properties are in a state ready for when the user resets the password in the future. So kind of a loop determining and updating the state of the password reset and first logins after resetting the password.

enter image description here

Lastly

Your AspnetUsers table should look as below

enter image description here

Comments

This is how I would approach it. I have not tested it so you may have modify it if you encounter exception. It is all also hard coded to show the approach to solved the problem.

Trichoid answered 5/2, 2016 at 20:19 Comment(6)
You seem to have the very same image pasted twice. Also, am I not mistaken to believe your approach closes only the one session that is open but fails if there are more sessions open (two, three) - the very fist one open session reauthenticates but the rest of them still works without authentication.Cyclist
@Wiktor thanks, I have updated the image and added some comments.Trichoid
-1, this is not helpful, this does not prevent saved passwords in other browsers. Also if you login again somewhere else, you are resetting your HasResetPassword field back to false, by doing so, you are still allowing other logged in sessions continue with same old password.Maribelmaribelle
Saved passwords from any web browser will not work because the password has been reset. From your comments, I know you have not implemented nor tested it. @Jackhammer asked the question and as you can see from his comment he is very happy with the solution.Trichoid
when we change the current password, the saved password is useless. but my concerns are is this process is efficient and generic. to make your answer best, it needs all users commentsJackhammer
Sorry, what I mean is, this does not work with "RememberMe" option where cookies are persisted (Kind of remember me on server side). This will only work if persistent cookies are not used.Maribelmaribelle
D
22

I saw you are using ASP.NET Identity 2. What you are trying to do is already built in. All you need to do is change the SecurityStamp and all previous authentication cookies are no longer valid.

After you change the password you also need to change the SecurityStamp:

await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword);
await UserManager.UpdateSecurityStampAsync(User.Identity.GetUserId());

If you want the user to remain logged in, you have to reissue a new authentication cookie (signin):

    await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

Otherwise the user/session who initated the password change will also be logged out.

And to log out all other sessions immediately you need to lower the check interval in the config:

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.FromSeconds(1),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

Steps to reproduce:

  1. Created a new Asp.Net Web App in VS2015.
  2. Choose MVC template.
  3. Edit App_Stat/Startup.Auth.cs, line 34: change validateInterval: TimeSpan.FromMinutes(30) to validateInterval: TimeSpan.FromSeconds(1)
  4. Edit Controllers/ManageController.cs, line 236: add the UserManager.UpdateSecurityStampAsync method call.
  5. Run project, create a user, login, open a different browser and also login.
  6. Change password, refresh the page in the other browser : you should be logged out.
Dossal answered 17/3, 2016 at 3:4 Comment(3)
have you try this methodJackhammer
Yes. I added Steps to reproduce in the above answer. It's what I did to test.Dossal
I always wondered what the security stamp was used for. Thanks for the helpful answer!Vouvray
T
8

So I got home and decided to put together some code. Show me the code !!!

I would use a handler so the verification is always done when the user first access the application and it is done at one place for every action method access.

The idea is when the user reset their password, the application records the user has reset their password and have not logged in for the first time and sign out the user.

user.HasResetPassword = true;
user.IsFirstLoginAfterPasswordReset = false;

When the user signs in, the application verifies if the user had previously reset their password and is now signing in for the first time. If these statements are valid the application updates its records to say you have not reset your password and you are not signing in for the first time.

Step 1

Add two properties to ApplicationUser model

enter image description here

Step 2

Add a class AuthHandler.cs in Models folder with the implementation below. At this stage you verify if the user has reset their password and has not logged in for the first time since the password was reset. If this is true, redirect the user to the login.

enter image description here

Step 3

In RouteConfig.cs call the AuthHandler so that it is invoked for each incoming http request to your application. enter image description here

Step 4

In ResetPassword method add implementation as below. At this step when a user has reset their password update the properties to say , they have reset their password and have not logged in for the first time. Notice the user is also signed out explicitly when they reset their password.

enter image description here

Step 5

In Login method add the implementation below. At this step if a user logins in successfully, verify their password was reset and they has logged for the first time is false. If all the conditions are true, update the properties in the database, so the properties are in a state ready for when the user resets the password in the future. So kind of a loop determining and updating the state of the password reset and first logins after resetting the password.

enter image description here

Lastly

Your AspnetUsers table should look as below

enter image description here

Comments

This is how I would approach it. I have not tested it so you may have modify it if you encounter exception. It is all also hard coded to show the approach to solved the problem.

Trichoid answered 5/2, 2016 at 20:19 Comment(6)
You seem to have the very same image pasted twice. Also, am I not mistaken to believe your approach closes only the one session that is open but fails if there are more sessions open (two, three) - the very fist one open session reauthenticates but the rest of them still works without authentication.Cyclist
@Wiktor thanks, I have updated the image and added some comments.Trichoid
-1, this is not helpful, this does not prevent saved passwords in other browsers. Also if you login again somewhere else, you are resetting your HasResetPassword field back to false, by doing so, you are still allowing other logged in sessions continue with same old password.Maribelmaribelle
Saved passwords from any web browser will not work because the password has been reset. From your comments, I know you have not implemented nor tested it. @Jackhammer asked the question and as you can see from his comment he is very happy with the solution.Trichoid
when we change the current password, the saved password is useless. but my concerns are is this process is efficient and generic. to make your answer best, it needs all users commentsJackhammer
Sorry, what I mean is, this does not work with "RememberMe" option where cookies are persisted (Kind of remember me on server side). This will only work if persistent cookies are not used.Maribelmaribelle
M
1

Even ASP.NET Authentication says clearly that you have to have a secondary check to confirm if user is still an active logged in user (for example, we could block the user, user may have changed his password), Forms Authentication ticket does not offer any security against these things.

UserSession has nothing to do with ASP.NET MVC Session, it is just a name here

The solution I have implemented is,

  1. Create a UserSessions table in the database with UserSessionID (PK, Identity) UserID (FK) DateCreated, DateUpdated
  2. FormsAuthenticationTicket has a field called UserData, you can save UserSessionID in it.

When User Logs in

public void DoLogin(){

     // do not call this ...
     // FormsAuthentication.SetAuthCookie(....

     DateTime dateIssued = DateTime.UtcNow;

     var sessionID = db.CreateSession(UserID);
     var ticket = new FormsAuthenticationTicket(
            userName,
            dateIssued,
            dateIssued.Add(FormsAuthentication.Timeout),
            iSpersistent,
            // userData
            sessionID.ToString());

     HttpCookie cookie = new HttpCookie(
         FormsAuthentication.CookieName,
         FormsAuthentication.Encrypt(ticket));
     cookie.Expires = ticket.Expires;
     if(FormsAuthentication.CookieDomain!=null)
         cookie.Domain = FormsAuthentication.CookieDomain;
     cookie.Path = FormsAuthentication.CookiePath;
     Response.Cookies.Add(cookie);

}

To Authorize User

Global.asax class enables to hook into Authorize

public void Application_Authorize(object sender, EventArgs e){
     var user = Context.User;
     if(user == null)   
         return;

     FormsIdentity formsIdentity = user.Identity as FormsIdentity;
     long userSessionID = long.Parse(formsIdentity.UserData);

     string cacheKey = "US-" + userSessionID;

     // caching to improve performance
     object result = HttpRuntime.Cache[cacheKey];
     if(result!=null){
         // if we had cached that user is alright, we return..
         return;
     }

     // hit the database and check if session is alright
     // If user has logged out, then all UserSessions should have been
     // deleted for this user
     UserSession session = db.UserSessions
           .FirstOrDefault(x=>x.UserSessionID == userSessionID);
     if(session != null){

          // update session and mark last date
          // this helps you in tracking and you
          // can also delete sessions which were not
          // updated since long time...
          session.DateUpdated = DateTime.UtcNow;
          db.SaveChanges();

          // ok user is good to login
          HttpRuntime.Cache.Add(cacheKey, "OK", 
               // set expiration for 5 mins
               DateTime.UtcNow.AddMinutes(5)..)

         // I am setting cache for 5 mins to avoid
         // hitting database for all session validation
         return;
     }

     // ok validation is wrong....


     throw new UnauthorizedException("Access denied");

}

When User Logs out

public void Logout(){

    // get the ticket..
    FormsIdentity f = Context.User.Identity as FormsIdentity;
    long sessionID = long.Parse(f.UserData);

    // this will prevent cookie hijacking
    var session = db.UserSessions.First(x=>x.UserSessionID = sessionID);
    db.UserSession.Remove(session);
    db.SaveChanges();

    FormsAuthentication.Signout();
}

When user changes password or user is blocked or user is deleted...

public void ChangePassword(){

    // get the ticket..
    FormsIdentity f = Context.User.Identity as FormsIdentity;
    long sessionID = long.Parse(f.UserData);

    // deleting Session will prevent all saved tickets from
    // logging in
    db.Database.ExecuteSql(
        "DELETE FROM UerSessions WHERE UserSessionID=@SID",
        new SqlParameter("@SID", sessionID));
}
Maribelmaribelle answered 21/3, 2016 at 6:10 Comment(1)
Brilliant , I took the idea and implemented my own solutionTwenty
T
0

The ASP.NET Identity authentication is dependent on cookies on the user's browser. Because you use two different browsers to test it. You will have two different authentication cookies.Until the cookies expire the user is still authenticated That is why you are getting that results.

So you will have to come with some custom implementation.

For instance, always check if the user's has reset the password and has not yet logged in for the first time with the new password. If they haven't, logout them out and redirect to login. When they login a new auth cookie will be created.

Trichoid answered 5/2, 2016 at 10:7 Comment(3)
got any idea for custom implementationJackhammer
Yes. Are you using Entity Framework Code First or Database First?Trichoid
I am using EF 6, asp.net 4.5.2, iis-8.5 and Identity 2Jackhammer
M
0

I modeled my approach around this article from Github's Blogs

Modeling your App's User Session

They use a Hybrid Cookie Store / DB approach using ruby but I ported it to My ASP .Net MVC project and works fine.

Users can see all other sessions and revoke them if needed. When a user resets password, any active sessions are revoked.

I use an ActionFilterAttribute on a base controller to check active sessions cookies. If session cookie is found to be stale the user is logged out and redirected to sign in.

Mcclees answered 5/2, 2016 at 13:1 Comment(0)
B
0

Based on CodeRealm's answer...

For anyone who experiences a situation where https access to your application on the browser throws a null pointer exception (i.e Object reference not set to an instance of an object.), it is because there might be existing records in your database where HasResetPassWord and/or IsFirstLoginAfterPasswordReset is null. Http requests will work, but https requests will fail, not sure why.

Solution: Just update the database manually and give both fields values. Preferably, false on both columns.

Bidwell answered 18/2, 2016 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.