为什么User.Identity.IsAuthenticated始终为false?
问题描述:
我对这个“愚蠢”的问题踌躇满志。我尝试查看用户是否在我的操作中进行了身份验证。我习惯像HttpContext.User.Identity.IsAuthenticated
那样做,但它总是返回false。我期待到AuthorizeAttribute
的代码,并且他们使用为什么User.Identity.IsAuthenticated始终为false?
protected virtual bool AuthorizeCore(HttpContextBase httpContext)
{
//removed code...
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated)
{
return false;
}
//removed code....
}
所以我的问题和困惑是,为什么不会在工作中我的行为?
我用Simplemembership,这是我的模板mvc4
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
{
return RedirectToLocal(returnUrl);
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
我在authorizationattribute使用使用默认登录在web.config
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider"
type="WebMatrix.WebData.SimpleRoleProvider,
WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider"
type="WebMatrix.WebData.SimpleMembershipProvider,
WebMatrix.WebData" />
</providers>
</membership>
林使用的设置和它的作品,所以我的问题是什么区别?
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
//code here....
if (httpContext.User.Identity.IsAuthenticated)
return true;
return true;
}
这是我在我的行动
public ActionResult Index()
{
//removed code....
if (HttpContext.User.Identity.IsAuthenticated)
{
return View();
}
// revmoved code...
return View();
}
答
使用我一般用Application_PostAuthenticateRequest
这不是一个过滤器。 请随时忽略我的CustomPrincipal
,你不必这样做。只需从我的一个项目中快速粘贴即可。
我没有看到你的代码FormsAuthentication
很难说为什么HttpContext.User
没有得到正确的设置。请发布您的FormsAuthentication
代码。
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
var serializeModel = (CustomPrincipalSerializeModel)
JsonSerializer.DeserializeFromString(authTicket.UserData,
typeof (CustomPrincipalSerializeModel));
var roles = serializeModel.Roles ?? new string[0];
var newUser = new CustomPrincipal(authTicket.Name, roles)
{
UserId = serializeModel.UserId,
UserName = serializeModel.UserName,
FirstName = serializeModel.FirstName,
LastName = serializeModel.LastName
};
HttpContext.Current.User = newUser;
}
}
如果不知道您的身份验证设置(可能在web.config中设置),很难回答 – 2013-03-13 19:50:09
身份验证Cookie尚未设置。见http://stackoverflow.com/questions/8660539/who-sets-the-isauthenticated-property-of-the-httpcontext-user-identity – Jasen 2013-03-13 20:11:32
@贾森,我没有看到他的登录方法,以确认他是否设置身份验证cookie甚至使用cookie。你看见什么了? – 2013-03-13 20:37:19