FormsAuthentication和Ajax请求

时间:2015-02-23 18:19:07

标签: asp.net-mvc asp.net-mvc-5 forms-authentication

我知道在从jQuery发送ajax请求时是否对用户进行了身份验证。

当用户从浏览器执行常规请求并设置HttpContext.User.Identity cookie时,

aspxauth不为空。当用户尝试从jQuery执行ajax请求时,aspxauth根本没有设置。

我的网站.Config

<authentication mode="Forms">
    <forms loginUrl="~/" />
</authentication>

设置FormsAuthentication Cookie

var cookie = new AuthCookie
            {
                UserId = user.UserId,
                Email = user.Email,
                Name = user.Name,
                RememberMe = createPersistentCookie,
                TimeZone = user.TimeZone,
                CompanyId = user.CompanyId,
                Roles = new List<string> { user.Role ?? "user" }
            };

            string userData = JsonConvert.SerializeObject(cookie);
            var ticket = new FormsAuthenticationTicket(1, cookie.Email, DateTime.Now,
                                                       DateTime.Now.Add(FormsAuthentication.Timeout),
                                                       createPersistentCookie, userData);
            string encTicket = FormsAuthentication.Encrypt(ticket);
            var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket) { Expires = DateTime.Now.Add(FormsAuthentication.Timeout) };

            _httpContext.Response.Cookies.Add(httpCookie);

当我通过我的broser提出请求时,会出现auth cookie: enter image description here

每当我使用$ .get()通过javascript发出请求或通过javascript加载javascript脚本/任何其他请求时,我得到: enter image description here

奇怪的是,在另一个ASP应用程序中,我正在使用WebSecurity并且完美无缺。 auth cookie始终从客户端发送回服务器。对于这个ASP MVC 5应用程序,当我尝试使用FormAuthentication时,我无法让AuthCookie继续处理所有请求。

1 个答案:

答案 0 :(得分:0)

您仍然可以使用[授权]等来装饰您的班级/方法。如果您正在查看控制器方法内部,则可以访问从System.Web.Mvc.Controller或System.Web.Http.ApiController继承的用户属性,具体取决于您的控制器风格:

//
// Summary:
//     Returns the current principal associated with this request.
//
// Returns:
//     The current principal associated with this request.
public IPrincipal User { get; set; }

它可以像这样使用:

if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
    // user has access - process request
}

编辑:

以下是带有ajax [able]方法的[Api]控制器的示例,该方法使用控制器的用户属性而不是HttpContext:

public class HelloController : ApiController
{
    [HttpGet]
    public IHttpActionResult HelloWorld()
    {
        try
        {
            if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
            {
                return Ok("Hello There " + User.Identity.Name + "!");
            }
           else
            {
                return Ok("Hello There Anonymous!");
            }
        }
        catch { throw; }
    }
}