nunu
nunu

Reputation: 3262

Session and Form Authentication Problem : Asp.Net MVC 3

As I am working on Asp.Net MVC 3 application, I have used FormAuthentication in my application.

The problem is, after logged in into system, when I close browser (without logout) and again open the page (let's say /Admin/ProductList/) in browser, the page is still being invoked and I got focus in my controller too. [Which is really bad! :( ]

What I want is, when I close browser and come back again on any page, it should goes to logged in page.

Please review the given code for your understanding.

public void SignIn(string userName, bool isCookiePersistent)
        {

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, userName, DateTime.Now, DateTime.Now.AddDays(14),
                createPersistentCookie, string.Empty);

            HttpCookie authCookie = FormsAuthentication.GetAuthCookie(userName, isCookiePersistent);
            if (authTicket.IsPersistent)
            {
                authCookie.Expires = authTicket.Expiration;
            }

            authCookie.Value = FormsAuthentication.Encrypt(authTicket);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }

public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

Web.Config code:

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

My page is getting in **Redirection Loop**: This is the main issue.

Am I missing any other settings or global.asax event handling?

Please help me by giving me any resolution.

Thanks in advance.

Upvotes: 1

Views: 5971

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039578

Here:

authCookie.Expires = authTicket.Expiration;

That's what makes the authentication cookie persistent and the browser stores it on the client computer so that when you restart the browser the cookie is still there. If you don't want persistent cookies you could try this:

public void SignIn(string userName)
{
    var authTicket = new FormsAuthenticationTicket(
        1, userName, DateTime.Now, DateTime.Now.AddDays(14), false, string.Empty
    );
    var authCookie = FormsAuthentication.GetAuthCookie(userName, false);
    authCookie.Value = FormsAuthentication.Encrypt(authTicket);
    HttpContext.Current.Response.Cookies.Add(authCookie);
}

Upvotes: 3

Related Questions