2012-11-08 23 views
1

我有以下的登錄方法在我的MVC項目Login方法中的User.Identity.IsAuthenticated是否可以返回true?

public ActionResult Login(LoginModel model, string returnUrl) 
    { 


     if (ModelState.IsValid) 
     { 


      if (_authenticationRepository.Login(model.UserName, model.Password)) 
      {      
       var authenticationTicket = new FormsAuthenticationTicket(1, model.UserName, DateTime.Now, 
                     DateTime.Now.AddMinutes(20), 
                     model.RememberMe, "", "/"); 

       var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
               FormsAuthentication.Encrypt(authenticationTicket)); 
       Response.Cookies.Add(cookie); 
       UserContext.CreateUserContext(); 
       return RedirectToLocal(returnUrl); 
      } 
     } 

UserContext.cs 此存儲用戶/權限到會話。

public static void CreateUserContext() 
    { 
     BuildUserContext(HttpContext.Current.User); 
    } 

    private static void BuildUserContext(IPrincipal principalUser) 
    { 
     if (!principalUser.Identity.IsAuthenticated) return; 

     var user = _userAccountsRepository.GetUserByUserName(principalUser.Identity.Name); 

     if (user == null) return; 

     var userContext = new UserContext { IsAuthenticated = true }; 

     var siteUser = Mapper.Map(user); 

     userContext.SiteUser = siteUser; 

     HttpContext.Current.Session["UserContext"] = userContext; 
    } 

我知道IsAuthenticated只會重定向後成爲現實。所以在我的login()方法中,是否可以確保principalUser.Identity.IsAuthenticated將返回true?

或者還有什麼地方可以創建用戶上下文,如果不是它的登錄方法?

我想要實現的是:在

    1. 用戶登錄,如果登錄成功,爲他的角色/權限查詢數據庫,並將其保存到一個會話,以便我沒有每次檢查用戶是否有權訪問特定操作時都需要重新查詢。
  • 回答

    0

    你可以做類似如下:

    當用戶首次登錄時,得到用戶的角色/權限的詳細信息,序列化,並將其存儲在會話中。因此,當這個會話在內存中時,每次你想檢查用戶是否具有操作權限時,都會從內存反序列化它,而不是進入數據庫。

    相關問題