Avatar of Robert Treadwell
Robert Treadwell
Flag 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
ASP.NETVisual Basic.NET

Avatar of undefined
Last Comment
Robert Treadwell

8/22/2022 - Mon
Nasir Razzaq

Did you step through the code to see which of the if conditions is being executed?
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.
Nasir Razzaq

>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?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
SOLUTION
guru_sami

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Robert Treadwell

ASKER
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
Robert Treadwell

ASKER
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
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Robert Treadwell

ASKER
This solution is what fix my issue.  There could be another way.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.