2015-02-23 110 views
1

从jQuery发送ajax请求时,我知道用户是否已通过身份验证。FormsAuthentication和Ajax请求

HttpContext.User.Identity当用户从其浏览器发出常规请求并设置了aspxauth cookie时,它不为空。当用户尝试从jQuery执行ajax请求时,根本没有设置aspxauth

我的web.config

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

设置FormsAuthentication饼干

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提出请求时,会出现身份验证的cookie: enter image description here

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

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

回答

0

你仍然可以使用[Authorize]等来修饰你的类/方法。如果你正在寻找检查控制器方法里面,你有机会获得财产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的[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; } 
    } 
} 
+0

当对象来自ajax请求时未设置用户 – 2015-02-23 20:31:50

+0

此User对象不是来自HttpContext,而是直接来自控制器。当调用任何控制器方法时,无论请求是什么“类型”,它都会被解析。我假设你的ajax请求正在调用控制器方法正确? – pnm 2015-02-23 21:10:20

+0

目前,我正在使用名为'CustomAuth'的Action的授权属性ontop来检查用户是否为null,然而,当我正在执行ajax请求时,它始终为空。不要将HttpContext传递给我的属性? – 2015-02-23 21:29:54