[英]Why do I get User.Identity.IsAuthenticated false
我得到的User.Identity.IsAuthenticated
為false。 我認為這是造成我的第二個問題:我無法使用[Authorize]
裝飾器訪問控制器。
我的代碼去了:
我的MembershipProvider
繼承,以及ValidateUser
的實現:
public override bool ValidateUser(string username, string password) { if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) return false; var user = DBManager.Context.Usuarios.First(x => x.Nombre == username); if (user.Pass != password) return false; return true; }
我的Web.Config
身份驗證部分:
<authentication mode="Forms"> <forms loginUrl="~/Account/Login" defaultUrl="~/" timeout="20" slidingExpiration="true" /> </authentication> <membership defaultProvider="Membership"> <providers> <clear /> <add name="Membership" type="SGKS.Security.Membership" /> </providers> </membership>
我Contorller
:
[HttpGet] [AllowAnonymous] public ActionResult Login() { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Facutra"); } return View(); } [HttpPost] [AllowAnonymous] public ActionResult Login(Login model) { if (ModelState.IsValid) { if (System.Web.Security.Membership.ValidateUser(model.Nombre, model.Pass)) { FormsAuthentication.SetAuthCookie(model.Nombre, model.Recordarme); } ViewBag.Error = "Usuario y/o contraseña incorrectos."; } return View(model); }
我在這里找到了答案:
當您在成功進行身份驗證時調用
FormsAuthentication.SetAuthCookie
時,您FormsAuthentication.SetAuthCookie
身份驗證cookie添加到響應中 。 該cookie將存儲在客戶端瀏覽器中,並在后續請求中發送。 因此,只有在后續請求下,該用戶才被視為已認證。 因此,您需要在調用SetAuthCookie
方法之后始終進行重定向。
換句話說,您需要在調用FormsAuthentication.SetAuthCookie
之后立即添加RedirectToAction
。
[HttpPost]
[AllowAnonymous]
// The ASP.NET framework automatically puts a returnUrl query string parameter of the original
// page the user requested. You just need to add that parameter here to gain access to it
// (assuming you want to redirect the user back to the original requested page rather than
// some start page).
public ActionResult Login(Login model, string returnUrl)
{
if (ModelState.IsValid)
{
if (System.Web.Security.Membership.ValidateUser(model.Nombre, model.Pass))
{
FormsAuthentication.SetAuthCookie(model.Nombre, model.Recordarme);
// Redirect so the next request can see the user as authenticated
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
ViewBag.Error = "Usuario y/o contraseña incorrectos.";
}
return View(model);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.