加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 如何在不使用FormsAuthentication.RedirectFromLogin

发布时间:2020-12-15 18:51:16 所属栏目:asp.Net 来源:网络整理
导读:我使用表单身份验证,并向服务器发送Aajx请求进行身份验证。基于json结果,客户端决定去哪里和做什么。这是我不使用FormsAuthentication.RedirectFromLoginPage不干扰ajax / json响应的原因。 在这种情况下,即使在使用Membership.ValidateUser验证用户后,R
我使用表单身份验证,并向服务器发送Aajx请求进行身份验证。基于json结果,客户端决定去哪里和做什么。这是我不使用FormsAuthentication.RedirectFromLoginPage不干扰ajax / json响应的原因。

在这种情况下,即使在使用Membership.ValidateUser验证用户后,Request.IsAuthenticated也返回false。然后我设置cookie使用

FormsAuthentication.SetAuthCookie(username,false);

虽然第二个参数,持久cookie,是false,cookie仍然有效跨浏览器会话。

任何想法如何使Request.IsAuthenticated工作,而不使用FormsAuthentication.RedirectFromLoginPage?

解决方法

您需要更新请求的当前安全主体。当您调用Response。重定向(…)一个新的请求完成,安全主体被重新初始化,并且Request.IsAuthenticated在你的case返回true。 FormsAuthentication.RedirectFromLoginPage内部调用响应。重定向(…)。您可以手动更新当前请求的安全主体,如下所示:
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);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读