【问题标题】:How to disable or enable cookie when using FormsAuthentication in ASP.NET webforms?在 ASP.NET 网络表单中使用 FormsAuthentication 时如何禁用或启用 cookie?
【发布时间】:2012-10-23 19:23:03
【问题描述】:

我需要使用 FormsAuthentication 来验证使用 ajax 的用户的登录,我知道我不能使用 FormsAuthentication.RedirectFromLoginPage("UserName",false) 因为使用 ajax 时没有重定向。
我可以使用什么来设置此用户已授权。
尝试使用:

FormsAuthentication.SetAuthCookie("UserName", false);

但是这里有 cookie,我不想使用 cookie。

谢谢

【问题讨论】:

    标签: asp.net jquery forms-authentication


    【解决方案1】:

    您可以将表单身份验证的加密/解密/过期方面与请求/响应周期(例如 cookie)分开使用。

    例如:您可以像这样以字符串形式获取身份验证令牌:

    // create a ticket for "myusername" which expires in 15 minutes
    string authToken = FormsAuthentication.Encrypt(new FormsAuthenticationTicket("myusername", false, 15));
    

    然后,当使用通过某种自定义方法从用户那里接收它时(您并没有真正指定要使用什么来代替 cookie),您使用FormsAuthentication.Decrypt 来检查它是否有效。请注意,您必须捕获异常检查 null 以检查有效性。

    // decrypt receivedAuthToken string which was received somehow in your request
    FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(receivedAuthToken);
    

    但您也必须自己管理续订流程:

    var newTicket = FormsAuthentication.RenewTicketIfOld(authTicket);
    var newToken = FormsAuthentication.Encrypt(newTicket)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-09-17
      • 2011-03-30
      • 1970-01-01
      • 2022-01-12
      • 2010-09-15
      相关资源
      最近更新 更多