简体   繁体   中英

Increase the time of asp.net forms Authentication Even I change Time in web.config file its not working

Below is My Web.config File Code I am using forms Authentication. I increased the Time out Time but still its not working with in 2 minutes My Application is Getting log out Automatically Again User had to sign in Again .

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <connectionStrings>

        <add name="DBCS" connectionString="Data Source=105.55.191.106;Initial Catalog=Trucks;User ID=Girish;Password=Girish123!@#" />
        <add name="Truck_ManagementConnectionString" connectionString="Data Source=105.55.191.106;Initial Catalog=Trucks;User ID=Girish;Password=Girish123!@#;" providerName="System.Data.SqlClient" />
      </connectionStrings>
      <system.webServer>

        <defaultDocument>
          <files>
            <clear />
            <add value="HomeMain.aspx" />
          </files>
        </defaultDocument>
        <httpErrors errorMode="Detailed" />
        <asp scriptErrorSentToBrowser="true" />
        <validation validateIntegratedModeConfiguration="false" />
        <modules runAllManagedModulesForAllRequests="true">
          <remove name="UrlRoutingModule" />
          <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </modules>
        <handlers>
          <add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web,   Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        </handlers>
      </system.webServer>
      <system.web>
        <sessionState timeout="60" />
        <trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false" />
        <customErrors mode="Off" />
        <authentication mode="Forms">
          <forms loginUrl="HomeMain.aspx"  timeout="2880" defaultUrl="NewtrucksValidations.aspx">
            <credentials passwordFormat="Clear">
              <user name="Rajesh" password="Rajesh" />
              <user name="Rajesh1" password="Rajesh1" />
            </credentials>
          </forms>
        </authentication>
        <authorization>
          <deny users="?" />
        </authorization>
        <compilation debug="true" targetFramework="4.0" />
        <pages buffer="true" enableEventValidation="false"></pages>
      </system.web>
      <system.net>

      </system.net>
      <appSettings>

        <add key="microsoft.visualstudio.teamsystems.aspnetdevserver:/dxfsd" value="2772;True;4952;1;-8587766731921818473" />
        <add key="microsoft.visualstudio.teamsystems.backupinfo" value="1;web.config.backup" />
        <add key="token" value="AFcWxV21C7fd0v3bYYYRCpSSRl31AZ8FkzH5YTJtR8RVkxY6oiRdbOtN" />
        <add key="paypalemail" value="akshithrajesh290-facilitator_api1.gmail.com" />
        <!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
        <add key="PayPalSubmitUrl" value="https://www.sandbox.paypal.com/cgi-bin/webscr" />
        <add key="FailedURL" value="http://localhost:49666/PayPalIntegration/Failed.aspx" />
        <!--Failed Page URL-->
        <add key="SuccessURL" value="http://localhost:49666/Default.aspx" />
        <!--Success Page URL-->
      </appSettings>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"></assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="v11.0" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
    </configuration>

May be this is because of there is no machinekey specified. You can give it a try -

Application pools can regularly be recycled. When recycling occurs, the ASP.NET will recreate a MachineKey , if there isn't one specified in web.config . Machine key is used to generate Authentication ticket, so the newly recreated machinekey makes the current Authentication ticket invalid which causes users to logout. The solution to that is to add a <machinekey> section in the web.config file.

<system.web>

<machineKey validationKey="19127329C4588866D1120D7146F4C6A7B53F29DBEF58F890" decryptionKey="789AA0B220798EF1780914BBE9CCB681C285F31680014162" validation="SHA1" />

</system.web>

There are many tools for generating machinekey. you may try - http://www.developerfusion.com/tools/generatemachinekey/

Try setting the time when you creating the Authorisation cookie:

    Private Sub CreateAuthorisationCookie(ByVal Role As String)
    ' Create and tuck away the cookie
    Dim authTicket As New FormsAuthenticationTicket(1, txtUsername.Text, _
                                                    DateTime.Now, _
                                                    DateTime.Now.AddMinutes(15), False, Role, FormsAuthentication.FormsCookiePath)
    Dim encTicket As String = FormsAuthentication.Encrypt(authTicket)
    Dim faCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encTicket)
    Response.Cookies.Add(faCookie)

End Sub

The Custom Identity Class Imports System.Data

Imports System.Configuration

Imports System.Web

Imports System.Web.Security

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.WebControls.WebParts

Imports System.Web.UI.HtmlControls

Public Class CCustomIdentity
    Implements System.Security.Principal.IIdentity


    Private _ticket As FormsAuthenticationTicket

    Public Sub New(ticket As FormsAuthenticationTicket)



        _ticket = ticket
    End Sub

    Public ReadOnly Property AuthenticationType() As String Implements System.Security.Principal.IIdentity.AuthenticationType


        Get
            Return "Custom"
        End Get
    End Property


    Public ReadOnly Property IsAuthenticated() As Boolean Implements System.Security.Principal.IIdentity.IsAuthenticated


        Get
            Return True
        End Get
    End Property


    Public ReadOnly Property Name() As String Implements System.Security.Principal.IIdentity.Name


        Get
            Return _ticket.Name
        End Get
    End Property


    Public ReadOnly Property Ticket() As FormsAuthenticationTicket


        Get
            Return _ticket
        End Get
    End Property


    Public ReadOnly Property CompanyName() As String


        Get


            Dim userDataPieces As String() = _ticket.UserData.Split("|".ToCharArray())


            Return userDataPieces(0)
        End Get
    End Property


    Public ReadOnly Property Title() As String


        Get


            Dim userDataPieces As String() = _ticket.UserData.Split("|".ToCharArray())


            Return userDataPieces(1)
        End Get
    End Property


End Class

The Custom Principal Class

Imports System.Data
Imports System.Configuration

Imports System.Web

Imports System.Web.Security

Imports System.Web.UI

Imports System.Web.UI.WebControls

Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls

Public Class CCustomPrincipal
    Implements System.Security.Principal.IPrincipal


    Private _identity As CCustomIdentity

    Public Sub New(identity As CCustomIdentity)



        _identity = identity
    End Sub

    Public ReadOnly Property Identity() As System.Security.Principal.IIdentity Implements System.Security.Principal.IPrincipal.Identity


        Get
            Return _identity
        End Get
    End Property


    Public Function IsInRole(role As String) As Boolean Implements System.Security.Principal.IPrincipal.IsInRole


        Return False

    End Function

End Class

My Global.asax methods

   Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires upon attempting to authenticate the use
        ' Get the authentication cookie
        Dim cookieName As String = FormsAuthentication.FormsCookieName
        Dim authCookie As HttpCookie = Context.Request.Cookies(cookieName)

        ' If the cookie can't be found, don't issue the ticket
        If authCookie Is Nothing Then
            Return
        End If

        ' Get the authentication ticket and rebuild the principal 
        ' & identity
        Dim authTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
        Dim roles As String() = authTicket.UserData.Split(New [Char]() {"|"c})
        Dim userIdentity As New GenericIdentity(authTicket.Name)
        Dim userPrincipal As New GenericPrincipal(userIdentity, roles)
        Context.User = userPrincipal
    End Sub

  Private Sub Global_asax_PostAuthenticateRequest(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PostAuthenticateRequest
        ' Get a reference to the current User

        Dim usr As IPrincipal = HttpContext.Current.User

        ' If we are dealing with an authenticated forms authentication request

        If usr.Identity.IsAuthenticated AndAlso usr.Identity.AuthenticationType = "Forms" Then


            Dim fIdent As FormsIdentity = TryCast(usr.Identity, FormsIdentity)

            ' Create a CustomIdentity based on the FormsAuthenticationTicket  

            Dim ci As New CCustomIdentity(fIdent.Ticket)

            ' Create the CustomPrincipal

            Dim p As New CCustomPrincipal(ci)

            ' Attach the CustomPrincipal to HttpContext.User and Thread.CurrentPrincipal

            HttpContext.Current.User = p


            Threading.Thread.CurrentPrincipal = p
        End If
    End Sub

And Finally my Main Web.config

    <authentication mode="Forms">
  <forms loginUrl="~/Login.aspx" cookieless="UseCookies" name=".ASPXFORMSAUTH" protection="All" slidingExpiration="true" timeout="15" defaultUrl="~/Login.aspx">
    <!--SlidingExpiration=timeout reset with each request
              Timeout in minutes
              Protection=validation and encryption=ALL-->
  </forms>
</authentication>
<authorization>
  <deny users="?" />
</authorization>

So with that in place i am able to control the timeout. Hope it helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM