问题
I have a login control on an aspx page - mydomain.cloudapp.net/Login.aspx. My login page is running in azure and I have written code for the Page_Load, Login_authenticate and OnLoggedIn routines in login.aspx.vb.
The website has an offline html5 application cache which is checked / refreshed when the page is loaded. I don't think this is affecting the operation of the login. The cache state is 'idle' when I attempt to log in.
My web.config configuration for my membership is:
<authentication mode="Forms">
<forms loginUrl="Login.aspx" name=".ASPNETAUTH" protection="None" path="/" timeout="25" cookieless="UseCookies" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
<customErrors mode="Off" />
<roleManager enabled="true" defaultProvider="CustomizedProvider">
<providers>
<clear />
<add name="CustomizedProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="aspConnectionString" applicationName="MyApplication" />
</providers>
</roleManager>
<membership defaultProvider="CustomizedProvider" userIsOnlineTimeWindow="25">
<providers>
<clear />
<add name="CustomizedProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="aspConnectionString" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="MyApplication" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="1" passwordAttemptWindow="10" passwordStrengthRegularExpression="" />
</providers>
</membership>
My login control looks like this:
<asp:Login ID="LoginUser" runat="server"
DestinationPageUrl="~/Users/reports.html" OnAuthenticate="Login_authenticate" OnLoggedIn="OnLoggedIn">
<LayoutTemplate>
<div>
<asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">User Name:</asp:Label>
<asp:TextBox ID="UserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="ctl00$LoginUser">*</asp:RequiredFieldValidator>
</div>
<div>
<asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label>
<asp:TextBox ID="Password" runat="server" TextMode="Password"></asp:TextBox>
<asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="ctl00$LoginUser">*</asp:RequiredFieldValidator>
</div>
<div id="FailText">
<asp:Literal ID="FailureText" runat="server" EnableViewState="False"></asp:Literal>
</div>
<div>
<asp:Button CssClass="btn btn-blue min-width input-large LoginButton" ID="LoginButton" runat="server" CommandName="Login" Text="Log In" ValidationGroup="ctl00$LoginUser" />
</div>
</LayoutTemplate>
</asp:Login>
I sometimes get a problem where the login fails. Looking at my console and database logs the behaviour seems to be as follows:
- I open the browser page
- I enter a username and password
- I select Login
Result:
No database logs have been added, which indicates that the Page_Load, Login_authenticate and OnLoggedIn routines have not run.
My console log shows that the browser appears to have navigated from mydomain.cloudapp.net to Login.aspx - i.e. console logs that were labelled mydomain.cloudapp.net are now labelled Login.aspx and vice versa
The browser remains on mydomain.cloudapp.net/Login.aspx and shows a blank login box
- I enter a username and password
- I select Login
Result:
My database logs show that the user has been logged in. There are logs to show this which were created in my Page_Load, Login_authenticate and OnLoggedIn routines.
My console log shows that the browser appears to have navigated from Login.aspx to mydomain.cloudapp.net - i.e. console logs that were labelled Login.aspx are now labelled mydomain.cloudapp.net and vice versa.
The browser remains on mydomain.cloudapp.net/Login.aspx and shows a blank login box
- I enter a username and password
- I select Login
Result: The user is logged in
This behaviour only seems to happen when I first open the page. Once the page is up and running I can log in and out without problems. Can anyone explain what is going on here and how I can get users logged in first time?
UPDATE: I've just realised that my database logs don't record any log messages from the Page_Load routine until after Step 5 above. So when I first navigate to the page there is no Page_Load log record and when I first attempt to log in there is no log record, although the console logs indicate that the page has refreshed. Finally, after step 5 Page_Load records a log message, followed by log messages from Login_authenticate and OnLoggedIn. However the user is not redirected to 'reports.html' at this stage, even though the user is now authenticated. It is only after the third login attempt that the user is redirected. My login.aspx.vb routines look like this:
Private Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim sDetails2 As String = ""
If HttpContext.Current.User.Identity.IsAuthenticated Then
sDetails2 = "User authenticated"
Else
sDetails2 = "User not authenticated"
FormsAuthentication.SignOut()
End If
Dim sDetails As String = "Login.aspx - Page_Load"
Dim iLogType As Integer = WaspWAVB.con.ciLogLogin
Dim iInspection As Nullable(Of Integer) = Nothing
Dim iCompany As Nullable(Of Integer) = Nothing
WaspWAVB.SysUtilities.AddLog(HttpContext.Current.Session, HttpContext.Current.Request, iLogType, sDetails, sDetails2, iInspection, iCompany, Nothing)
End Sub
Protected Sub Login_authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs)
Dim loginU As Login = Me.FindControl("LoginUser")
Dim mu As MembershipUser = Membership.GetUser(loginU.UserName, False)
If mu IsNot Nothing Then
If mu.IsLockedOut Then
If mu.LastLockoutDate.AddMinutes(15) < Now() Then
Dim bLockedOut As Boolean = mu.UnlockUser()
End If
End If
End If
e.Authenticated = Membership.ValidateUser(loginU.UserName, loginU.Password)
If Not e.Authenticated Then
Dim sDetails As String = "Login.aspx - Login_authenticate"
Dim sDetails2 As String = "User not authenticated: " & loginU.UserName & " - " & loginU.Password
Dim iLogType As Integer = WaspWAVB.con.ciLogLogin
Dim iInspection As Nullable(Of Integer) = Nothing
Dim iCompany As Nullable(Of Integer) = Nothing
WaspWAVB.SysUtilities.AddLog(HttpContext.Current.Session, HttpContext.Current.Request, iLogType, sDetails, sDetails2, iInspection, iCompany, Nothing)
Else
Dim sDetails As String = "Login.aspx - Login_authenticate"
Dim sDetails2 As String = "User authenticated: " & loginU.UserName & " - " & loginU.Password
Dim iLogType As Integer = WaspWAVB.con.ciLogLogin
Dim iInspection As Nullable(Of Integer) = Nothing
Dim iCompany As Nullable(Of Integer) = Nothing
WaspWAVB.SysUtilities.AddLog(HttpContext.Current.Session, HttpContext.Current.Request, iLogType, sDetails, sDetails2, iInspection, iCompany, Nothing)
End If
End Sub
Sub OnLoggedIn(ByVal sender As Object, ByVal e As EventArgs)
Dim loginU As Login = Me.FindControl("LoginUser")
Dim pc As WaspWAVB.ProfileCommon = New WaspWAVB.ProfileCommon
pc.Initialize(loginU.UserName, True)
Dim iCompany As Int32 = CInt(pc.CompanyID)
Dim authCookie As HttpCookie = FormsAuthentication.GetAuthCookie(loginU.UserName, False)
Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
Dim newTicket As FormsAuthenticationTicket = New FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, iCompany.ToString)
authCookie.Value = FormsAuthentication.Encrypt(newTicket)
Response.Cookies.Add(authCookie)
Dim sDetails As String = "Login.aspx - OnLoggedIn"
Dim sDetails2 As String = "Logged in:" & loginU.UserName
Dim iLogType As Integer = WaspWAVB.con.ciLogLogin
Dim iInspection As Nullable(Of Integer) = Nothing
WaspWAVB.SysUtilities.AddLog(HttpContext.Current.Session, HttpContext.Current.Request, iLogType, sDetails, sDetails2, iInspection, iCompany, Nothing)
End Sub
来源:https://stackoverflow.com/questions/39617496/asp-net-login-fails-on-first-and-second-call