表单身份验证不能与jQuery一起使用

时间:2016-12-13 05:49:14

标签: asp.net

我正在进行表单身份验证,如下所示:

                if (strRole != null)
            {
                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                   1,                            // version
                   username,                      // user name
                   DateTime.Now,                 // create time
                   DateTime.Now.AddSeconds(500),  // expire time
                   false,                        // persistent
                   strRole);                     // user data

                string strEncryptedTicket = FormsAuthentication.Encrypt(ticket);
                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, strEncryptedTicket);
                Context.Response.Cookies.Add(cookie);
                return true;
            }

然后在另一个页面上我有jQuery如下

$.ajax({
    type: "POST",
    crossOrigin: true,
    url: "./WebService.asmx/Login",
    data: JSON.stringify({'username':username,'password':password}),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {
        if (response.d === true) {
            $(location).attr('href', '/dash/dashboard.aspx')
        }
        else {
            ShowErrorModal("Invalid login or password.","login");
        }
    }
});

问题出在dashboard.aspx页面的on_load事件中,以下内容始终为false

HttpContext.Current.User.Identity.IsAuthenticated

问题是它认为用户未经过身份验证。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

添加以下内容解决了global.asax.cs中的问题

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        string cookieName = FormsAuthentication.FormsCookieName;
        HttpCookie authCookie = Context.Request.Cookies[cookieName];

        if (authCookie == null)
        {
            return;
        }
        FormsAuthenticationTicket authTicket = null;
        try
        {
            authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        }
        catch
        {
            return;
        }
        if (authTicket == null)
        {
            return;
        }
        string[] roles = authTicket.UserData.Split(new char[] { '|' });
        FormsIdentity id = new FormsIdentity(authTicket);
        GenericPrincipal principal = new GenericPrincipal(id, roles);

        Context.User = principal;
    }

取自https://stackoverflow.com/a/8490241/1144596