locked
formsauthenticationticket is decrypted with previous login data RRS feed

  • Question

  • User799396372 posted

    in my mvc application i have implemented user authentication with active directory membership. after a user login a FormsAuthenticatedTicket is created and encrypted and in Application_PostAuthenticateRequest the ticket is decrypted and the deserialized userdata was stored in custom principal object. my probleme is when a user login again after expiration of cookie, the ticked is encrypted with current login ticket data, but in global.asax the ticket of previouse login still decrypted because when debug i have seen the ticket data of previous login of same user

    Why? have I made mistakes?

    i have read the custom forms authentification tutoriels but I did not completely understand

    in web config

     <authentication mode="Forms">
      <forms name=".ADAuthCookie" loginUrl="~/Account/Login">
      </forms>
    </authentication>
    
    <membership defaultProvider="ADMembershipProvider">  
      <providers>
        <clear/>
        <add name="ADMembershipProvider" 
          type="System.Web.Security.ActiveDirectoryMembershipProvider" 
          connectionStringName ="ADconnectionString"
          attributeMapUsername="sAMAccountName" />  
    
      </providers>  
    </membership>  

    my post action login methode

    [HttpPost]
        [AllowAnonymous]
        public ActionResult Login(string userName, string password, bool rememberMe, string returnUrl)
        {
    
            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                ViewBag.Message = FormattedMessage.GetFormattedMessage("Veuillez Entrer l'utilisateur et/ou mot passe", TypeMessage.Danger, true);
                return this.View();
            }
    
            if (Membership.ValidateUser(userName, password))
            {
                FormsAuthentication.SetAuthCookie(userName, rememberMe);
                //JavaScriptSerializer js = new JavaScriptSerializer();
                PrincipalContext principalContext = new PrincipalContext(ContextType.Domain); 
                var userAD = UserPrincipal.FindByIdentity(principalContext, userName);
                var intervenant = unitOfWorkBll.UserBLL.GetAllFiltered(u => u.Matricule == userAD.EmployeeId, includes: "IntervenantRoles.Role, IntervenantStructures.Structure").SingleOrDefault();
                //string userData = js.Serialize(intervenant);
                string userData = JsonConvert.SerializeObject(intervenant, Formatting.Indented, new JsonSerializerSettings {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                });
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddMinutes(10),rememberMe, userData);
    
                string encryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    
                Response.Cookies.Add(cookie);
                if (!string.IsNullOrWhiteSpace(returnUrl) )
                {
                    return this.Redirect(returnUrl);
                }
    
                return this.RedirectToAction("Index", "Home");
            }
    
            ViewBag.Message= FormattedMessage.GetFormattedMessage("l'utilisateur et /ou le mot passe incorrect.", TypeMessage.Danger, true);
    
            return this.View();
        }

    in global asax

    protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie autoCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
    
            if (autoCookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(autoCookie.Value);
                Intervenant user = JsonConvert.DeserializeObject<Intervenant>(ticket.UserData/*, new JsonSerializerSettings {
                    PreserveReferencesHandling = PreserveReferencesHandling.Objects
                }*/);
    
                CustomADPrincipal customADPrincipal = new CustomADPrincipal(user); ;
    
                HttpContext.Current.User = customADPrincipal;
            }
    
        }

    Wednesday, November 6, 2019 2:18 PM

Answers

  • User799396372 posted

    i found the source of probleme : i have used the eager loading so the length of userdata is more large, there for the ticket could not be decrypted that's why a cookie is null in global asax

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 14, 2019 2:10 PM

All replies

  • User665608656 posted

    Hi Beginner,

    According to your description, I used the code you provided to use forms authentication ticket for testing.

    When the expiration time is reached, I log in again for validation. The previously stored information has disappeared, and there is no problem with the previous login information you mentioned.

    I suggest you check the expiration time of the cookie and debug it to see if there is a issue.

    Best Regards,

    YongQing.

    Thursday, November 7, 2019 6:32 AM
  • User799396372 posted

    i have changed the expiration date of ticket from AddMinute(30) to AddMenute(10)

    when decryption i get the ticket data of the previous expiration date (after 30 minute not 10 minutes) of the same user with ticket version decrypted to 2.

    Sunday, November 10, 2019 9:01 AM
  • User475983607 posted

    i have changed the expiration date of ticket from AddMinute(30) to AddMenute(10)

    when decryption i get the ticket data of the previous expiration date (after 30 minute not 10 minutes) of the same user with ticket version decrypted to 2.

    The browser does not send expired cookies to the server.  You must have other issues with your code.  Please use the Visual Studio debugger to test your code.  Otherwise, share code that reproduces this issue with the community.

    Sunday, November 10, 2019 3:41 PM
  • User799396372 posted

    i resolved this problem with removing FormsAuthentication.SetAuthCookie(userName, rememberMe); because i have used the FormsAuthenticationTicket object

    but I am in front of another problem: in global asax Application_PostAuthenticateRequest, when trying to reading the cookie, i have found by debugger that's null although the cookie added with ticket encrypted successfuly

    string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
    
            Response.Cookies.Add(cookie); 

    i have two users : this probleme occurs with one of them but with the other there's no probleme

    please, how to resolve this problem?

    Tuesday, November 12, 2019 2:39 PM
  • User665608656 posted

    Hi Beginner,

    According to your description, one of the users can store the cookie normally, which means that your code is no problem.

    You need to confirm that the browser used by another user who cannot use the stored cookie has disabled the cookie function.

    If the browser does not enable the cookie function, the stored cookie cannot be obtained in the code.

    Here is a way to enable cookie settings in different browsers. You can refer to the following link:

    Enable Cookies in Your Web Browser

    Best Regards,

    YongQing.

    Wednesday, November 13, 2019 8:01 AM
  • User799396372 posted

    i found the source of probleme : i have used the eager loading so the length of userdata is more large, there for the ticket could not be decrypted that's why a cookie is null in global asax

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 14, 2019 2:10 PM