2016-11-28 52 views
0

当我创建我的formsauthenticationticket时,Application_AuthenticateRequest(在global.asax中)不立即被触发。当我检查user.isrole时,它是空的。但稍后当我尝试其他操作时,将触发Application_AuthenticateRequest,并设置用户的角色。Application_AuthenticateRequest触发到后端

登录功能:

 if (loggedIn) 
      { 
       ViewBag.loginFailed = 1; 
       string roles = "Administrator"; 
       CreateTicket(pharmacist.ID.ToString(), roles); 
       LoginRedirect(); 
      } 

方法:

[Authorize(Roles = "Administrator, User")] 
    private void CreateTicket(string id, string role) 
    { 

     var ticket = new FormsAuthenticationTicket(
       version: 1, 
       name: id, 
       issueDate: DateTime.Now, 
       expiration: DateTime.Now.AddHours(1), 
       isPersistent: false, 
       userData: role); 

     var encryptedTicket = FormsAuthentication.Encrypt(ticket); 
     var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
     HttpContext.Response.Cookies.Add(cookie); 
    } 

    [Authorize(Roles = "Administrator, User")] 
    private ActionResult LoginRedirect() { 
     if (User.IsInRole("Administrator")) 
     { 
      return RedirectToAction("Index", "Pharmacist"); 
     } 
     else if (User.IsInRole("User")) 
     { 
      return RedirectToAction("Index", "Patient"); 
     } 
     else { 
      return RedirectToAction("Logout", "Authentication"); 
     } 
    } 

Application_AuthenticateRequest

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
    { 
     if (HttpContext.Current.User != null) 
     { 
      if (HttpContext.Current.User.Identity.IsAuthenticated) 
      { 
       if (HttpContext.Current.User.Identity is FormsIdentity) 
       { 
        FormsIdentity id = 
         (FormsIdentity)HttpContext.Current.User.Identity; 
        FormsAuthenticationTicket ticket = id.Ticket; 

        // Get the stored user-data, in this case, our roles 
        string userData = ticket.UserData; 
        string[] roles = userData.Split(','); 
        HttpContext.Current.User = new GenericPrincipal(id, roles); 
       } 
      } 
     } 
    } 

回答

2

Application_AuthenticateRequest只叫你时要求新资源。

在你的情况下,你仍然在创建FormsAuthenticationTicket的请求。因此,主要对象尚未分配给当前线程。

如果您想从当前线程检索IPrincipal,则需要明确指定它。

var encryptedTicket = FormsAuthentication.Encrypt(ticket); 
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); 
// You need this two lines. 
HttpContext.Current.User = new GenericPrincipal(id, roles); 
Thread.CurrentPrincipal = HttpContext.Current.User; 
.... 

还要确保您有内部Application_AuthenticateRequest这两个线。

protected void Application_AuthenticateRequest(Object sender, EventArgs e) 
{ 
    ... 
    HttpContext.Current.User = new GenericPrincipal(id, roles); 
    Thread.CurrentPrincipal = HttpContext.Current.User; <-- Do not forget this. 
    ... 
} 

FYI:你不需要AuthorizeAttribute的私有方法。你只需要它在控制器或操作方法。

[Authorize(Roles = "Administrator, User")] <-- This is not needed. 
private void CreateTicket(string id, string role) 
{ 
    ... 
}