2016-09-01 39 views
1

我正在構建使用Windows身份驗證的Intranet站點,但使用實體框架存儲授權聲明。沒有用戶登錄。如果瀏覽器關閉(cookie被刪除)並且應用程序重新啓動(CNTRL F5),Home/Index控制器會檢查用戶WindowsIdentity是否已註冊,並且應該登錄該用戶。ASP.NET核心SignInAsync需要瀏覽器刷新

public async Task<IActionResult> Index() 
    { 
     string userWin = WindowsIdentity.GetCurrent().Name.Split('\\')[1]; 
     var user = await _userManager.FindByNameAsync(userWin); 
     if (user != null) 
     { 
      await _signInManager.SignInAsync(user, isPersistent: false); 
      string userHTTP = HttpContext.User.Identity.Name; 
      ViewData["Message"] = $"Registered User: {user} and HTTPUser: {userHTTP} is registered for this site"; 
     } 
     else 
      ViewData["Message"] = "Please contact admin to register for this website"; 

     return View(); 
    } 

第一次運行時,userHTTP爲空,並且需要用戶登錄的查看html不會執行。如果瀏覽器刷新,那麼一切正常。爲什麼登錄和HTTPContext需要刷新?

回答

1

此行爲是「按設計」。從文檔:ASP.NET Core提供了cookie中間件,它將用戶主體序列化爲加密的cookie,然後在隨後的請求中驗證cookie,重新創建主體並將其分配給HttpContext上的User屬性。 由於這是一個使用Windows身份驗證的Intranet站點,站點註冊用戶可以在沒有登錄重定向的情況下登錄用戶視圖。索引函數被重定向到自己以模擬後續請求:

  string userHTTP = User.Identity.Name; 
      if (userHTTP == null) 
      { //will be null on first request with new cookie. Rerun the request. 
       await _signInManager.SignInAsync(user, isPersistent: false); 
       return RedirectToAction(nameof(HomeController.Index), "Home"); 
      } 
      else 
       ViewData["Message"] = $"Registered User: {user} and HTTPUser: {userHTTP} is registered for this site"; 

我對所有這些都是陌生的。如果不熟悉,請添加評論。