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

前端 未结 4 533
闹比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:14

    Redirecting after a POST is best practice, and should be considered the correct solution.

    In some cases, you may still want to find out whether a user is authenticated within the scope of the authentication request (for instance if you are running additional logic after the authentication was performed which is shared with other requests).

    In this case, you can reset the value of Request.IsAuthenticated with the following code:

    // set the forms auth cookie
    FormsAuthentication.SetAuthCookie(username, createPersistentCookie);
    
    // reset request.isauthenticated
    var authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        if (authTicket != null && !authTicket.Expired)
        {
            var roles = authTicket.UserData.Split(',');
            System.Web.HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(authTicket), roles);
        }
     }
    

    See post here: http://abadjimarinov.net/blog/2010/01/24/RenewUserInTheSameRequestInAspdotNET.xhtml

提交回复
热议问题