2014-01-13 11 views
5

您好我想獲得一個用戶的作用,將其設置爲一個cookie在我的應用MVC4我怎麼設置cookie,然後重定向到一個動作

我有下面的代碼工作

public ActionResult Index() 
    { 
     var user = User.Identity.Name; // set by 3rd party central login in manager 

     // key to check that we are in our environment with 3rd party login set up 
     if (ConfigurationManager.AppSettings["IsNGDC"] == "true") 
     { 
      // ActiveKey login 
      if (user.Contains("uid=")) 
      { 
       var endIndex = user.IndexOf(",ou"); 

       var userEmail = user.Substring(4, endIndex - 4); 
       user = userEmail; 
      } 

      SetAuthenticationCookie(user); 
     } 

     // view model is not needed I could just pass in a string 
     var viewModel = new SiteminderViewModel { Username = user }; 

     if (ModelState.IsValid) 
     { 
      this.AssignRoles(viewModel); 
      return this.View(); 
     } 

     return View(viewModel); 
    } 

我需要改變這一點,因爲我使用的動態導航欄根據用戶角色顯示不同的項目,直到用戶刷新頁面才顯示正確的導航欄。我認爲這是因爲視圖使用了cookie,並且視圖以與設置cookie相同的動作呈現。

我想在我的控制器這分成2個行動如下

public void LogIn() 
    { 
     var user = User.Identity.Name; // set by 3rd party central login in manager 

     // key to check that we are in our environment with 3rd party login set up 
     if (ConfigurationManager.AppSettings["IsNGDC"] == "true") 
     { 
      // ActiveKey login 
      if (user.Contains("uid=")) 
      { 
       var endIndex = user.IndexOf(",ou"); 

       var userEmail = user.Substring(4, endIndex - 4); 
       user = userEmail; 
      } 

      SetAuthenticationCookie(user); 
     } 

     // view model is not needed I could just pass in a string 
     var viewModel = new SiteminderViewModel { Username = user }; 

     this.AssignRoles(viewModel); 

     // default URL in Index action for this controller 
     this.Response.Redirect(FormsAuthentication.DefaultUrl, false); 
    } 

    public ActionResult Index() 
    { 
     ViewBag.Message = "Home App Description here"; 
     return this.View(); 
    } 

當我嘗試這樣它看起來像餅乾還沒有確定。不幸的是,由於第三方登錄,我只能在生產環境的複製上測試此代碼,所以我的調試信息有限。據我所知,問題似乎與我如何重定向有關。

我已經提供了使用cor創建cookie並分配角色的方法。

附加信息

private void SetAuthenticationCookie(string username) 
    { 
     var tkt = new FormsAuthenticationTicket(1, username, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(20), true, string.Empty); 
     var encryptedTkt = FormsAuthentication.Encrypt(tkt); 

     var formsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTkt); 
     this.Response.Cookies.Add(formsCookie); 
    } 

    private void AssignRoles(SiteminderViewModel viewModel) 
    { 
     var authCookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; 
     var ticket = authCookie != null ? FormsAuthentication.Decrypt(authCookie.Value) : new FormsAuthenticationTicket(1, viewModel.Username, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(20), true, string.Empty); 
     var user = this.userRepository.GetUser(viewModel.Username); 

     if (user != null) 
     { 
      var principleProperties = new PrincipleProperties(ticket.UserData) 
      { 
       UserName = user.Email, 
       UserRole = user.UserGroup.Role.Name.Replace(" ", string.Empty), 
       ContextId = contextRepository.GetContextByDataOwnerGroupId(user.UserGroupId) 
      }; 

      if (user.DeletedIndicator) 
      { 
       principleProperties.UserRole = string.Empty; 
      } 

      this.SetPrinciple(ticket, principleProperties); 
     } 
    } 

    private FormsAuthenticationTicket SetPrinciple(FormsAuthenticationTicket ticket, PrincipleProperties properties) 
    { 
     var newticket = new FormsAuthenticationTicket(
      ticket.Version, 
      ticket.Name, 
      ticket.IssueDate, 
      ticket.Expiration, 
      ticket.IsPersistent, 
      properties.Serialize(), 
      ticket.CookiePath); 

     var encryptedTkt = FormsAuthentication.Encrypt(newticket); 

     var formsCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTkt); 
     this.Response.Cookies.Set(formsCookie); 

     var referenceDataIdentity = new ReferenceDataIdentity(ticket); 
     var principle = new ReferenceDataPrinciple(referenceDataIdentity, properties); 

     Thread.CurrentPrincipal = principle; 
     return newticket; 
    } 
+0

如何根據cookie過濾視圖?簡單如果其他? –

+0

我正在使用MVC sitemap提供程序,它使用每個操作的安全註釋來顯示導航欄到合適的人 –

+0

我只是想知道這是由於Cookie保存在瀏覽器中,但代碼在LogIn中是在服務器端創建cookie,但是因爲LogIn重定向到另一個操作而不是返回視圖,Cookie沒有到達瀏覽器? –

回答

3

這個問題的解決是沒有被添加到瀏覽器cookie的,因爲我之前重定向的餅乾到達客戶端的解決方案是讓登錄行動返回空白視圖,然後從視圖中重定向到Index操作我的代碼的最終版本結束瞭如下注意:登錄改變的authenticateUser

public ActionResult Index() 
    { 
     var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; 
     if (authCookie != null) 
     { 
      var ticket = FormsAuthentication.Decrypt(authCookie.Value); 

      if (ticket != null && ticket.UserData != string.Empty) 
      { 
       return this.View(); 
      } 
     } 

     return RedirectToAction("AuthenticateUser"); 
    } 

    public ActionResult AuthenticateUser() 
    { 
     // set by Site minder 
     var user = User.Identity.Name; 

     // ActiveKey login 
     if (user.Contains("uid=")) 
     { 
      var endIndex = user.IndexOf(",ou"); 

      var userEmail = user.Substring(4, endIndex - 4); 
      user = userEmail; 
     } 

     SetAuthenticationCookie(user); 


     var viewModel = new SiteminderViewModel { Username = user }; 

     this.AssignRoles(viewModel); 
     return this.View(); 
    } 

和視圖是。沒有HTML顯示,因此重定向不明顯。

@{ 
    ViewBag.Title = "AuthenticateUser"; 
    Layout = null; 
    Response.Redirect(Url.Action("Index", "Home"), false); 
} 

此代碼正在檢查是否存在Cookie並且用戶數據不是空的,如果這些檢查通過它會向用戶顯示主頁。否則,它將重定向到驗證操作,該操作將獲取我們的第三方中央登錄軟件在瀏覽器中設置的電子郵件地址,並從用戶詳細信息中獲取用戶詳細信息。如果用戶不在我們的用戶表中,則他們被賦予基本的訪問權限。

相關問題