我正在尝试编写一个 Login 方法,对用户进行身份验证并授权他们进入使用 ASP.NET MVC 4 开发的网站。问题是,尽管我在 Login 方法内验证用户并重定向到 ViewProfile 操作后调用 FormsAuthentication.SetAuthCookie 方法, User.Identity.IsAuthenticated 在我的自定义 Authorize 属性对象中仍然返回 false。
我给出了下面的代码:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginModel model)
{
if (Membership.ValidateUser(model.Username, model.Password))
{
FormsAuthentication.SetAuthCookie(model.Username, model.RememberMe);
return this.RedirectToAction("ViewProfile");
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
[MyAuthorize(Roles = "Super Role, Seeker")]
public ActionResult ViewProfile()
{
if (ModelState.IsValid)
{
...
}
}
这是授权属性类的代码
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
return false;
...
}
}
我缺少什么?
对于可能使用 FormsAuthentication 并面临类似情况的人,请确保您的 web.config 文件下存在以下配置
<authentication mode="Forms"></authentication>
现在一切正常
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)