Ami*_*ami 26 asp.net authentication ajax json asp.net-membership
我正在使用表单身份验证并向服务器发送Aajx请求以进行身份验证.根据json结果,客户决定去哪里和做什么.这就是我没有使用FormsAuthentication.RedirectFromLoginPage来干扰ajax/json响应的原因.
在这种情况下,即使在使用Membership.ValidateUser验证用户之后,Request.IsAuthenticated也会返回false.然后我使用了设置cookie
FormsAuthentication.SetAuthCookie(username, false);
Run Code Online (Sandbox Code Playgroud)
虽然第二个参数persistent cookie是false,但cookie在浏览器会话中仍然有效.
知道如何在不使用FormsAuthentication.RedirectFromLoginPage的情况下进行Request.IsAuthenticated工作吗?
Bra*_*nov 24
您需要更新请求的当前安全主体.当您调用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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*son 20
FormsAuthentication.SetAuthCookie
方法为提供的用户名创建身份验证票证,并将其添加到响应的cookie集合中,如果使用的是cookie,则将其添加到URL.
参考:msdn
看一下Forms Authentication Control Flow.身份验证cookie设置为响应cookie集合,并且应该在http协议级别可观察(例如,使用FireCookie或Fiddler2来验证这一点).
会员资格仅验证用户名/密码.既不是会员也SetAuthCookie()不会修改当前请求.他们希望将cookie发送回调用者,下一个请求是类似属性IsAuthenticated返回true.
请注意,您可以覆盖和扩展这些自动使用自定义流程IIdentity和IPrincipal,并挂接到认证事件,如果你需要.
| 归档时间: |
|
| 查看次数: |
46511 次 |
| 最近记录: |