Not able to automatically login in asp.net mvc

1.1k Views Asked by At

I am new to ASP.NET MVC and want to know how does the automatic sign-in works in a forms authentication scenerio.

I developed an application where I am setting a cookie on sign-in and the user is able to access the application if authenticated. But, when he re-opens the login page, though he is not being logged out as such, he has to enter username and password again. Basically he should be automatically signed in as the cookie has not expired till then.

Someone on an earlier post commented that this should be working by default. Can anyone explain how? And why is it not working for me? I am using ASP.NET MembershipProvider to implement login mechanism. Below is the Login method -

[HttpPost]
[AllowAnonymous]
public void Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid && WebSecurity.Login(model.EMail, model.Password, persistCookie: model.RememberMe))
    {
        return;
    }

    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return;
}
1

There are 1 best solutions below

1
On BEST ANSWER

You can check if user already authenticate and redirect it

[HttpPost]
[AllowAnonymous]
public void Login(LoginModel model, string returnUrl)
{

    if (User.Identity.IsAuthenticated) 
           return RedirectToAction(...);

    if (ModelState.IsValid && WebSecurity.Login(model.EMail, model.Password, persistCookie: model.RememberMe))
    {
        return;
    }

    ModelState.AddModelError("", "The user name or password provided is incorrect.");
    return;
}