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?
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