how to set the forms authentication cookie path

2019-06-22 13:23发布

问题:

On the same IIS web site, I have two ASP.NET web applications called /foo and /bar. Both use forms authentication and I want users to be able to log in and out of both sites independently.

With the standard configuration for forms authentication, it seems to send a cookie path of "/" for the forms auth cookie. This means that when a user logs into /bar it logs him out of /foo which is undesirable behaviour for me.

The obvious solution seems to be this:

FormsAuthentication.RedirectFromLoginPage(username, false, Request.ApplicationPath);

This makes the forms auth cookie have the application path which allows the user to log into /foo and /bar independently :-) However there is a further and more nasty problem: If the user tries to log into /Foo (with a capital F), IIS directs them to the web application /foo, but they can never log in because the browser (chrome in this case) is case sensitive when deciding whether to send the cookie based on the cookie path.

This seems to be a common problem which every ASP.NET web app developer will face but I can't see a sensible solution for it. Please tell me i've missed something obvious?

Thanks

Andy

回答1:

I assume you have already solved this issue somehow, but since I stumbled upon this question I thought I should add my few cents.

To solve the issue use different cookie names in web.config. Something like:

<authentication mode="Forms">
  <forms name=".ASPXFORMSAUTH_FOO"
      loginUrl="public/login.aspx" cookieless="UseCookies" slidingExpiration="true"/>
</authentication>

and

<authentication mode="Forms">
  <forms name=".ASPXFORMSAUTH_BAR"
      loginUrl="public/login.aspx" cookieless="UseCookies" slidingExpiration="true"/>
</authentication>


回答2:

Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
      pUsernameEntered, _
      DateTime.Now, _
      DateTime.Now.AddMinutes(60), _
      True, _
      pOperatorID, _
      FormsAuthentication.FormsCookiePath)

    ' Encrypt the ticket.
    Dim encTicket As String = FormsAuthentication.Encrypt(ticket)

    'create a cookie with the encrypted ticket
    Dim authenticationCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encTicket)

    'only create a persistent cookie if ticket persistent is checked
    If (ticket.IsPersistent) Then
        'give the cookie an expiration date outside of the forms authentication encrypted ticket
        authenticationCookie.Expires = ticket.Expiration
    End If

    'save the cookie
    HttpContext.Current.Request.Cookies.Remove(".cookiename")
    Response.Cookies.Add(authenticationCookie)

In cookiename you can set you cookie name. and in AddMinutes you can set your minutes values currently it is 60.