ASP.NET MVC 4 User Authentication

此生再无相见时 提交于 2019-12-22 20:42:14

问题


I am trying to write a Login method that authenticates and authorizes users into my web site developed with ASP.NET MVC 4. The problem is, although I call the FormsAuthentication.SetAuthCookie method after validating the user inside the Login method and redirect to ViewProfile action, User.Identity.IsAuthenticated returns still false in my custom Authorize attribute object.

I gave the code below:

[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)
    {
    ...
    }
}

And here is the code of the MyAuthorizeAttribute class

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

        ...
    }
}

What am I missing?


回答1:


For the ones who may use FormsAuthentication and face a similar situation, be sure that the following configuration exists under your web.config file

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

Now everything works fine



来源:https://stackoverflow.com/questions/18447120/asp-net-mvc-4-user-authentication

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!