Asp.net

AuthenticationManager.SignIn() 未登錄

  • June 19, 2020

我可以從數據庫中獲取有效使用者,創建ClaimsIdentity並呼叫該SignIn方法而不會出錯。

public ActionResult SignInConformation(SignInModel model)
{
   if (ModelState.IsValid)
   {
       var user = _userManager.Find(model.Username, model.Password);

       if (user == null)
       {
           ModelState.AddModelError("", "Invalid username and\\or password");
       }
       else
       {
           _authenticationManager.SignOut();
           var claimsIdentity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
           _authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);
           return RedirectToAction("Index", "Home");
       }
   }

   return View();
}

但是,當我檢查使用者是否在這樣的視圖上登錄時:

<p>
   Current User: @if (User.Identity.IsAuthenticated)
                 {
                     @User.Identity.Name
                 }
                 else
                 {
                     @:Unknown
                 }
</p>

IsAuthenticated返回false

我錯過了AuthenticationType = DefaultAuthenticationTypes.ApplicationCookieOWIN 啟動課程:

var authenticationOptions = new CookieAuthenticationOptions
{
   LoginPath = new PathString("/Account/SignIn"),
   AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
};

appBuilder.UseCookieAuthentication(authenticationOptions);

遺憾的是沒有一個好的、有用的錯誤。我不喜歡默默失敗的程序。

我有同樣的問題 - 問題是我的家庭控制器受到保護

$$ Authorize(Roles = “Administrator”) $$屬性,而我試圖以使用者身份登錄。

引用自:https://stackoverflow.com/questions/33330994