Link to home
Start Free TrialLog in
Avatar of Robert Treadwell
Robert TreadwellFlag for United States of America

asked on

Forms Authentication does not Redirect

I have a login page where upon submit the user is returned to the login page per the defaultUrl setting in form tag in web.config file.  In my code I direct my page to redirect base on authenticated users role or authentication.  The onLoggedInEvent subroutine runs correctly however the page still redirects to the defaultUrl.  

I've read many of the formsAuthentication nuances but in the suggested solution of formsAuthenticate.GetRedirectUrl or RedirectFromLoginPage.  these will not work for me because I need to determine redirection path after authentication.

Is there any way to get this to work?  This all worked on windows asp.net 3.5 server now moving to windows asp.net 4.0.

web.config parameters:

      <authentication mode="Forms">
          <forms defaultUrl="Login.aspx" protection="All" name=".ASPXFORMSAUTH" loginUrl="Login.aspx" timeout="15" requireSSL="true" domain="mydomain.com"/>
      </authentication>
      <httpCookies requireSSL="true"/>
      <sessionState timeout="1"/>

Protected Sub onAuthenticatedEvent(ByVal sender As Object, ByVal e As AuthenticateEventArgs)
        Dim userNameTB As TextBox = CType(LoginView1.FindControl("ADCLogin").FindControl("UserName"), TextBox)
        Dim passwordTB As TextBox = CType(LoginView1.FindControl("ADCLogin").FindControl("Password"), TextBox)

        Try
            If Membership.ValidateUser(userNameTB.Text, passwordTB.Text) Then
                e.Authenticated = True
                FormsAuthentication.SetAuthCookie(userNameTB.Text, False)
                Session.RemoveAll()
                Session("authUserName") = userNameTB.Text
            End If

        Catch ex As Exception
            Response.Write("onAuthenticatedEvent produce the following error: " + ex.Message)
        End Try
    End Sub

    Protected Sub onLoggedInEvent(ByVal sender As Object, ByVal e As EventArgs)
        Dim userNameTB As TextBox = CType(LoginView1.FindControl("ADCLogin").FindControl("UserName"), TextBox)

            'Register Action buttons that are stored and selected in the forms Master Page
            'This code works in conjunction with the Event handler in the ListViewMasterPage VB code
            Dim master As MasterPages_FormsMasterPage = TryCast(Me.Master, MasterPages_FormsMasterPage)
        Try

            'Now Direct user based on Role
            If Roles.IsUserInRole(userNameTB.Text, "Administrator") Or Roles.IsUserInRole(userNameTB.Text, "Site Admin") Then
                redirectUrl = "~/Lists_Views/OrgEditView.aspx"
            ElseIf Roles.IsUserInRole(userNameTB.Text, "Assistant") Then
                redirectUrl = "~/Lists_Views/StaffEditView.aspx"
            ElseIf Roles.IsUserInRole(userNameTB.Text, "Temporary User") Then
                redirectUrl = "~/Forms/OrganizationKeeper.aspx"
            Else
                redirectUrl = "~/Lists_Views/ClientByName.aspx"
            End If

            Response.Redirect(redirectUrl, False)
        Catch ex As Exception
            Response.Write("OnLoggedInEvent produce the following error: " + ex.Message)
        End Try
    End Sub
Avatar of Nasir Razzaq
Nasir Razzaq
Flag of United Kingdom of Great Britain and Northern Ireland image

Did you step through the code to see which of the if conditions is being executed?
Avatar of Robert Treadwell

ASKER

Yes, I did.  If the test user has none of the role credentials then the else statement is selected and the same is working for all the other test users and their roles.  

I'm getting through the logged in routine correctly.
>else statement is selected and the same is working for all the other test users and their roles.  

Even if they are in one of the roles specified above?
SOLUTION
Avatar of guru_sami
guru_sami
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I tried functionality with the 'formsauthentication' commented out.  Still same issue.  I added the following changes to the 'onauthenicationevent' subroutine as seen below.  In localhost everything worked as design.  The only difference between test environment from production.  Web.config required SSL is set to false.  I know this is  a big difference, i'm still not convenience this is causing my problem.

I do agree that I am being redirecting to defaultUrl and the cookie is being lost.  I'm unsure why.  

Any help is appreciated.  This has become a 3 day issue.


web.config:
      <authentication mode="Forms">
          <forms protection="All" name=".ASPXFORMSAUTH" loginUrl="Login.aspx" timeout="15" requireSSL="true" domain="domainname.com"/>
      </authentication>
      <httpCookies requireSSL="true"/>
      <sessionState timeout="1"/>
    <!--Since the 'protection' variable in the Forms tag is set to 'All' then we must set the Machine Key parameters Validation Key to SHA1 -->
    <machineKey validationKey="###Validation Key### went here"
                decryptionKey="###decryption Key### went here"
                validation="SHA1" decryption="AES"/>
    <!--Memeber ship Class -->
    <membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15">
      <providers>
        <remove name="AspNetSqlProvider"/>
        <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="adcsaspnetdbConnectionString" applicationName="*ApplicationName*" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" passwordFormat="Hashed"/>
      </providers>
    </membership>
    <!--Role Management goes here-->
    <roleManager enabled="true" cacheRolesInCookie="true" defaultProvider="SqlProvider" cookieProtection="All">
      <providers>
        <add connectionStringName="adcsaspnetdbConnectionString" applicationName="*ApplicationName*" name="SqlProvider" type="System.Web.Security.SqlRoleProvider" />
      </providers>
    </roleManager>

VB-Code:
    Protected Sub onAuthenticatedEvent(ByVal sender As Object, ByVal e As AuthenticateEventArgs)

        Dim userNameTB As TextBox = CType(LoginView1.FindControl("ADCLogin").FindControl("UserName"), TextBox)
        Dim passwordTB As TextBox = CType(LoginView1.FindControl("ADCLogin").FindControl("Password"), TextBox)
        Dim rememberUserName As CheckBox = CType(LoginView1.FindControl("ADCLogin").FindControl("RememberMe"), CheckBox)
        Try
            If Membership.ValidateUser(userNameTB.Text, passwordTB.Text) Then
                'e.Authenticated = True
                'FormsAuthentication.SetAuthCookie(userNameTB.Text, True)
                Session.RemoveAll()
                Session("authUserName") = userNameTB.Text
                Dim userRoles As Array = Roles.GetRolesForUser(userNameTB.Text)
                Dim ticket As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
                  userNameTB.Text, _
                  DateTime.Now, _
                  DateTime.Now.AddMinutes(20), _
                  rememberUserName.Checked, _
                  userRoles(0), _
                  FormsAuthentication.FormsCookiePath)

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

                ' Create the cookie.
                Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, encTicket))

            End If

        Catch ex As Exception
            Response.Write("onAuthenticatedEvent produce the following error: " + ex.Message)
        End Try
    End Sub
Please review previous post.  web.config and login.aspx.vb code.  

As I was trying to determine how to resolve this problem this is what I found, maybe this will help clarify my issue.  For right now this seems to be a production issue on godaddy.com windows server using 4.0 framework with SSL.

When I try to log in with username and password the login page seems to perform a return.  As indicated before, I believe the users membership is validated but the cookie or the user is not being save in session.  My code Validates and then creates a formsauthenticationticket followed by adding that to Response.Cookie.  In test environment all of this works well.

What I did notice if I select the only top-level link in my navigator pain, which direct me to another page the Url returns a 'ReturnUrl=' string.  When I try to log in after this happens I am able to login.  However, the username does not show up on the login page and none of my sub links appear until I press the only top-level link again.  After which, the user name appears on the login page and the site works as designed.  Followed by the user and the user's role function correctly as it is suppose to.

Can anyone help explain to me why this may be occurring and how can I fix it?

Thank you for your help
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
This solution is what fix my issue.  There could be another way.