Search code examples
asp.net-mvcc#-4.0forms-authentication

FormsAuthentication in MVC 4 : Once the user is authenticated login page should not be opened


I implemented FormsAuthentication in MVC4 application.

<authentication mode="Forms">
  <forms loginUrl="~/Home/Index" timeout="1"  />
</authentication>

private void SetupFormsAuthTicket(string userName, bool persistanceFlag)
        {
            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                                    userName,
                                    DateTime.Now,
                                    DateTime.Now.AddMinutes(1),
                                    persistanceFlag, ""
                                    );

            string encTicket = FormsAuthentication.Encrypt(authTicket);
            this.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
        }

Also, I can modify timeout in case system is idle, page will redirect to login page.

Now what I need is that if the user has successfully logged in then Login page should not be opened if user enters the login url in browser.

How to achieve the same ?


Solution

  • At the top of your login page, add the following razor code:

    @if (Request.IsAuthenticated)
    {
        Response.Redirect(Url.Action("Index", "Home"));
    }
    

    Replace Index and Home with the action/controller of your choice. This will cause the page to redirect if the user is authenticated.