我正在使用表单身份验证并向服务器发送 Aajx 请求进行身份验证。根据 json 结果,客户端决定去哪里以及做什么。这就是我不使用 FormsAuthentication.RedirectFromLoginPage 来不干扰 ajax/json 响应的原因。
在这种情况下,即使在使用 Membership.ValidateUser 验证用户之后,Request.IsAuthenticated 也会返回 false。然后我使用设置cookie
FormsAuthentication.SetAuthCookie(username, false);
尽管第二个参数持久性 cookie 为 false,但该 cookie 在跨浏览器会话中仍然有效。
知道如何在不使用 FormsAuthentication.RedirectFromLoginPage 的情况下使 Request.IsAuthenticated 工作吗?
您需要更新请求的当前安全主体。你打电话时Response. Redirect(...)
完成新请求并重新初始化安全主体,并且 Request.IsAuthenticated 在您的情况下返回 true 。FormsAuthentication.RedirectFromLoginPage
内部调用Response. Redirect(...)
。您可以手动更新当前请求的安全主体,如下所示:
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);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)