增加 asp.net 表单身份验证的时间即使我更改 web.config 文件中的时间它也不起作用
Increase the time of asp.net forms Authentication Even I change Time in web.config file its not working
下面是我的 Web.config 文件代码,我正在使用表单身份验证。我增加了超时时间,但它仍然无法在 2 分钟内使用我的应用程序再次自动注销用户必须再次登录。
<?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>
可能是因为没有指定 machinekey
。你可以试一试 -
应用程序池可以定期回收。当回收发生时,ASP.NET 将重新创建一个 MachineKey
,如果没有在 web.config
中指定的话。 Machine key用于生成Authentication ticket,因此重新创建的machinekey会使当前的Authentication ticket失效,导致用户退出。解决方案是在 web.config
文件中添加一个 <machinekey>
部分。
<system.web>
<machineKey validationKey="19127329C4588866D1120D7146F4C6A7B53F29DBEF58F890" decryptionKey="789AA0B220798EF1780914BBE9CCB681C285F31680014162" validation="SHA1" />
</system.web>
生成机器密钥的工具有很多。你可以试试 - http://www.developerfusion.com/tools/generatemachinekey/
尝试在创建授权 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
自定义身份 Class
进口 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
自定义委托人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
我的Global.asax方法
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
最后是我的主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>
因此,我可以控制超时。希望对你有帮助。
下面是我的 Web.config 文件代码,我正在使用表单身份验证。我增加了超时时间,但它仍然无法在 2 分钟内使用我的应用程序再次自动注销用户必须再次登录。
<?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>
可能是因为没有指定 machinekey
。你可以试一试 -
应用程序池可以定期回收。当回收发生时,ASP.NET 将重新创建一个 MachineKey
,如果没有在 web.config
中指定的话。 Machine key用于生成Authentication ticket,因此重新创建的machinekey会使当前的Authentication ticket失效,导致用户退出。解决方案是在 web.config
文件中添加一个 <machinekey>
部分。
<system.web>
<machineKey validationKey="19127329C4588866D1120D7146F4C6A7B53F29DBEF58F890" decryptionKey="789AA0B220798EF1780914BBE9CCB681C285F31680014162" validation="SHA1" />
</system.web>
生成机器密钥的工具有很多。你可以试试 - http://www.developerfusion.com/tools/generatemachinekey/
尝试在创建授权 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
自定义身份 Class 进口 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
自定义委托人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
我的Global.asax方法
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
最后是我的主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>
因此,我可以控制超时。希望对你有帮助。