How to set Request.IsAuthenticated to true when not using FormsAuthentication.RedirectFromLoginPage?

前端 未结 4 425
闹比i
闹比i 2021-01-30 22:40

I am using Form Authentication and sending an Aajx request to the server for authentication. Based on the json result, the client decides where to go and what to do. That is the

4条回答
  •  离开以前
    2021-01-30 23:00

    You need to update the current security principal for the request. When you call Response. Redirect(...) a new request is done and the security principal is reinitialized and Request.IsAuthenticated returns true in your case. FormsAuthentication.RedirectFromLoginPage internally calls Response. Redirect(...). You can manually renew the security principal for the current request like this:

    public void RenewCurrentUser()
    {
        System.Web.HttpCookie authCookie =
            System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = null;
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    
            if (authTicket != null && !authTicket.Expired)
            {
                FormsAuthenticationTicket newAuthTicket = authTicket;
    
                if (FormsAuthentication.SlidingExpiration)
                {
                    newAuthTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
                }
                string userData = newAuthTicket.UserData;
                string[] roles = userData.Split(',');
    
                System.Web.HttpContext.Current.User =
                    new System.Security.Principal.GenericPrincipal(new FormsIdentity(newAuthTicket), roles);
            }
        }
    }
    

提交回复
热议问题