2015-01-21 93 views
3

我正在嘗試使用基本表單身份驗證實現ASP.NET MVC5應用程序。 所以有我的登錄方法:401即使在FormsAuthentication.SetAuthCookie()後仍未授權

[HttpPost] 
    [AllowAnonymous] 
    public ActionResult Login(string email, string password, bool? rememberMe) 
    { 
     if (email.IsNullOrWhiteSpace() || password.IsNullOrWhiteSpace()) 
     { 
      return RedirectToAction("Index"); 
     } 

     UserEntity user = new UserEntity() {Email = email, PasswordHash = password}; 
     var userFromDb = _userService.FindUser(user); 
     if (userFromDb != null) 
     { 
      FormsAuthentication.SetAuthCookie(userFromDb.Name, rememberMe.GetValueOrDefault()); 

      var a = HttpContext.User.Identity.IsAuthenticated; //This is still false for some reson 
      return RedirectToAction("Index", "User"); 
     } 

     return RedirectToAction("Index"); 
    } 

但在重定向這種方法後馬上給的我401 Unauthorized錯誤。 也似乎像HttpContext.User.Identity.IsAuthenticated是錯誤的。

你有什麼想法/建議爲什麼它是這樣的,以及如何解決它?


UPD:我也有一條線webconfig概念從權威性,所以這不是一個理由

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

回答

7

我找到了原因。出於某種原因,在我的webconfig有一條線,這抑制FormsAuthentication模塊

<system.webServer> <modules> <remove name="FormsAuthentication" /> </modules> </system.webServer>

所以這條線FormsAuthentiction不工作,但如果我們將其註釋掉或刪除,如預期的所有作品。

+2

這是因爲默認情況下MVC5不使用FormsAuthentication。它使用ASP.NET標識,因此它將刪除默認模板中的FormsAuthentication。當你替換它時,你沒有重新啓用FormsAuth。 – 2015-01-21 16:50:53

1

<authentication mode="Forms" />到你的web.config文件中<system.web>爲它觸發其影響。

+0

已經存在 – Ph0en1x 2015-01-21 08:46:48

+0

這就是我一直在尋找的東西,所以非常感謝! – JakobMillah 2017-04-24 12:04:02