【问题标题】:ASP.NET MVC 4 User AuthenticationASP.NET MVC 4 用户身份验证
【发布时间】:2013-08-29 02:52:00
【问题描述】:

我正在尝试编写一个登录方法来验证和授权用户进入我使用 ASP.NET MVC 4 开发的网站。问题是,尽管我在验证登录方法中的用户并重定向后调用了 FormsAuthentication.SetAuthCookie 方法对于 ViewProfile 操作,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)
    {
    ...
    }
}

这里是 MyAuthorizeAttribute 类的代码

[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;

        ...
    }
}

我错过了什么?

【问题讨论】:

  • 在重定向时,您能看到在后续调用中设置和发送的表单身份验证 cookie 吗?

标签: c# session asp.net-mvc-4 authorize-attribute


【解决方案1】:

对于可能使用 FormsAuthentication 并遇到类似情况的人,请确保您的 web.config 文件下存在以下配置

<authentication mode="Forms"></authentication>

现在一切正常

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-24
    • 2013-07-22
    • 1970-01-01
    相关资源
    最近更新 更多