Question

When I go the my home page, [Authorize] tag redirects me to the login page (good!). But after I enter the credentials, seems like it just refreshes the login page (bad!).

Home Controller:

[Authorize]
public class HomeController : Controller
{
    public  ActionResult Index()
    {
        return View();
    }
    //other code
}

Account Controller:

[Authorize]
public class AccountController : Controller
{
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel loginModel, string returnUrl)
    {
        UserRoles userRoles = new UserRoles();
        UserRole userRole = userRoles.DbSet.FirstOrDefault(u => u.User == loginModel.UserName);

            if (ModelState.IsValid && Membership.ValidateUser(loginModel.UserName, loginModel.Password))
            {
                return RedirectToLocal(returnUrl);
            }

            ModelState.AddModelError("", "Bad login");            

           return View(loginModel);
    }
    //other code
}

Edit 1:

loginModel is passed in automatically after I fill out the login forms.

returnUrl is the previously visited url, in this case, it is the home controller. By default, it is also the home controller.

I think the problem might be caused by somehow not setting the user as authenticated so when it goes back to Home Controller, the [Authorize] tag activates again. What do you guys think?

Edit 2: In Global.asax.cs:

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

No custom route table here, everything is by default.

In Web.Config:

<authentication mode="Forms">
    <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

Correctly connected to my Login functions.

The membership authentication works, I have tested it.

Was it helpful?

Solution

Try this:

if (ModelState.IsValid && Membership.ValidateUser(loginModel.UserName, loginModel.Password))
{
    FormsAuthentication.SetAuthCookie(loginModel.UserName, true);
    return RedirectToLocal(returnUrl);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top