Search code examples
asp.net.netasp.net-mvcasp.net-identity

How to properly remove .AspNet.TwoFactorRememberBrowser cookie after disabling user's 2FA?


Microsoft.AspNet.Identity V2.2: When a user disables 2FA (from having previously been enabled) the user's cookie .AspNet.TwoFactorRememberBrowser remains and would potentially pose a security risk given the right circumstrances. I'm looking for a clean and appropriate way to remove the cookie for THAT user or should I just be changing the expiration date to something in the past - and if so how would I do that? I've googled a bunch all to no avail as if no one realizes that the cookie remains.


Solution

  • So in the absence of a better way, it looks like this will do the trick for Async Function /Manage/DisableTwoFactorAuthentication. Note that isPersistent = True removes the cookie while isPersistent = False just sets the expiration date back.

    ' POST: /Manage/DisableTwoFactorAuthentication
    <HttpPost>
    <ValidateAntiForgeryToken>
    Public Async Function DisableTwoFactorAuthentication() As Task(Of ActionResult)
        Await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), False)
        Dim userInfo = Await UserManager.FindByIdAsync(User.Identity.GetUserId())
        If userInfo IsNot Nothing Then
            Await SignInManager.SignInAsync(userInfo, isPersistent:=False, rememberBrowser:=False)
            Dim rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(userInfo.Id)
            AuthenticationManager.SignIn(New AuthenticationProperties With {
                .IsPersistent = True,   'False still leaves old cookie but with expired date
                .ExpiresUtc = Date.UtcNow.AddDays(-1)
            }, rememberBrowserIdentity)
        End If
        Return RedirectToAction("Index", "Manage")
    End Function
    

    Hope this helps someone! :-)