Avatar of Shade22
Shade22Flag for United States of America asked on

Login twice issues

When you log into my website, on the first time it boots you right back to the log in screen and displays the log in fields and also displays the logout button(only shows when your logged in.) along with displaying my username.  Once I log in again, it brings me to my dashboard. The default page in which the user logs in contains a masterpage in which I have included below.

MasterPage c#,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;

namespace MYSITE
{
    public partial class MYSITE : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            string userName = log_Master.UserName;
            string password = log_Master.Password;
            e.Authenticated = Membership.ValidateUser(log_Master.UserName, log_Master.Password);
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            if (Membership.ValidateUser(log_Master.UserName, log_Master.Password))
            {
                try
                {
                    ds_UserKey.SelectParameters["UserName"].DefaultValue = log_Master.UserName;
                    SqlDataReader Reader = (SqlDataReader)ds_UserKey.Select(DataSourceSelectArguments.Empty);
                    Reader.Read();
                    Session["accnt"] = Reader["accnt"].ToString();
                    Session["unlc"] = Reader["Local"].ToString();
                    Session["userName"] = log_Master.UserName.ToString();
                }
                catch
                {
                    var lb_loginError = (Label)log_Master.FindControl("lb_loginError");
                    lb_loginError.Text = "The Email or Password you provided is invalid.";
                    lb_loginError.ForeColor = System.Drawing.Color.White;
                }
            }
            else
            {
                var lb_loginError = (Label)log_Master.FindControl("lb_loginError");
                lb_loginError.Text = "The Email or Password you provided is invalid.";
                lb_loginError.ForeColor = System.Drawing.Color.White;
            }
        }

    }
}

Open in new window


Dashboard c#
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;

namespace MYSITE
{
    public partial class dashboard : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                    memberDataGet(Session["acct"].ToString(), "P1", Session["unlc"].ToString());
                    //Session["unlc"] = "0";
                    ace_Search.ContextKey = rbl_Search.SelectedValue + "/" + Session["unlc"].ToString();
                    div_AdminSearch.Visible = Roles.IsUserInRole("Site-Administrator");
                    div_EliteMember.Visible = Roles.IsUserInRole("EliteMember");
                
            }
            ace_Search.ContextKey = rbl_Search.SelectedValue + "/" + Session["unlc"].ToString();
        }

        protected void ddl_refresh(object sender, EventArgs e)
        {
            gv_LogHistory.Columns[4].Visible = true;
            gv_LogHistory.Columns[6].Visible = true;
            gv_LogHistory.Columns[3].Visible = true;
            gv_LogHistory.Columns[5].Visible = true;

            ds_work_hist.SelectParameters["pacct"].DefaultValue = Session["acct"].ToString();
            ds_work_hist.SelectParameters["pRtyp"].DefaultValue = null;
            ds_work_hist.SelectParameters["pRtyp"].DefaultValue = dd_plan.SelectedValue.ToString();
            ds_work_hist.SelectParameters["unlc"].DefaultValue = Session["unlc"].ToString();
           
            gv_WorkHistory.DataBind();
            if (dd_plan.SelectedValue.ToString() == "P5")
            {
                gv_LogHistory.Columns[4].Visible = false;
                gv_LogHistory.Columns[6].Visible = false;
            }
            else
            {
                gv_LogHistory.Columns[3].Visible = false;
                gv_LogHistory.Columns[5].Visible = false;
            }
        }

        protected void ddlPageSize_SelectedIndexChanged(Object sender, EventArgs e)
        {
            gv_WorkHistory.PageSize = Convert.ToInt32(ddl_PageSize.SelectedValue.ToString());

        }



        //protected void btn_memberSearch_Click(object sender, EventArgs e)
        //{
        //    ds_work_hist.SelectParameters["pRtyp"].DefaultValue = dd_plan.Text;
        //    SqlDataReader Reader = (SqlDataReader)ds_mbr_demo.Select(DataSourceSelectArguments.Empty);
        //    Reader.Read();
        //    lb_Fname.Text = Reader["ee_Fname"].ToString();
        //    lb_Mname.Text = Reader["ee_Mname"].ToString();
        //    lb_Lname.Text = Reader["ee_Lname"].ToString();
        //    lb_ee_strt.Text = Reader["ee_strt"].ToString();
        //    lb_ee_strt2.Text = Reader["ee_strt2"].ToString();
        //    lb_ee_city.Text = Reader["ee_city"].ToString();
        //    lb_ee_stat.Text = Reader["ee_stat"].ToString();
        //    lb_ee_zipc.Text = Reader["ee_zipc"].ToString();
        //    lb_ee_brdt.Text = Reader["ee_brdt"].ToString();
        //    lb_ee_sex.Text = Reader["ee_sex"].ToString();
        //}

        protected void memberDataGet(string acct, string Rtyp, string unlc)
        {
            try
            {
                //gv_WorkHistory.DataSource = null;
                ds_mbr_demo.SelectParameters["pacct"].DefaultValue = acct;
                ds_mbr_demo.SelectParameters["unlc"].DefaultValue = unlc;
                ds_work_hist.SelectParameters["pacct"].DefaultValue = acct;
                ds_work_hist.SelectParameters["pRtyp"].DefaultValue = Rtyp;
                ds_work_hist.SelectParameters["unlc"].DefaultValue = unlc;
                gv_WorkHistory.DataBind();
                Session["s_Plan"] = Rtyp;
                if (Session["s_Plan"].ToString() == "P5")
                {
                    gv_LogHistory.Columns[4].Visible = false;
                    gv_LogHistory.Columns[6].Visible = false;
                }
                else
                {
                    gv_LogHistory.Columns[3].Visible = false;
                    gv_LogHistory.Columns[5].Visible = false;
                }

                ds_mbrPlan.SelectParameters["pacct"].DefaultValue = acct;
                SqlDataReader Reader2 = (SqlDataReader)ds_mbrPlan.Select(DataSourceSelectArguments.Empty);
                Reader2.Read();
                Session["s_mbrPlan"] = Reader2["mbrPlan"].ToString();



                SqlDataReader Reader = (SqlDataReader)ds_mbr_demo.Select(DataSourceSelectArguments.Empty);
                Reader.Read();
                if (Reader.HasRows)
                {
                }
                else
                {
                    Session["s_mbrPlan"] = "";
                }
                tp_PensionPlan.Visible = Session["s_mbrPlan"].ToString().Contains("p") ? true : false;
                tp_BaseFund.Visible = Session["s_mbrPlan"].ToString().Contains("b") ? true : false;
                tp_International.Visible = Session["s_mbrPlan"].ToString().Contains("i") ? true : false;

                tp_Supplement.Visible = Session["s_mbrPlan"].ToString().Contains("s") ? true : false;
                dd_plan.Items.FindByValue("zz").Enabled = Session["s_mbrPlan"].ToString().Contains("p") ? true : false;
                dd_plan.Items.FindByValue("zd").Enabled = Session["s_mbrPlan"].ToString().Contains("d") ? true : false;
                dd_plan.Items.FindByValue("za").Enabled = Session["s_mbrPlan"].ToString().Contains("s") ? true : false;
                dd_plan.Items.FindByValue("dd").Enabled = Session["s_mbrPlan"].ToString().Contains("n") ? true : false;
                dd_plan.SelectedIndex = dd_plan.Items.IndexOf(dd_plan.Items.FindByValue("P1"));

                if (Reader.HasRows)
                {
                    lb_Fname.Text = Reader["ee_Fname"].ToString();
                    lb_Mname.Text = Reader["ee_Mname"].ToString();
                    lb_Lname.Text = Reader["ee_Lname"].ToString();
                    lb_ee_strt.Text = Reader["ee_strt"].ToString();
                    lb_ee_strt2.Text = Reader["ee_strt2"].ToString();
                    lb_ee_city.Text = Reader["ee_city"].ToString();
                    lb_ee_stat.Text = Reader["ee_stat"].ToString();
                    lb_ee_zipc.Text = Reader["ee_zipc"].ToString();
                    lb_ee_brdt.Text = Reader.IsDBNull(0) ? null : String.Format("{0:MM/dd/yyyy}", Reader["ee_brdt"]);
                    lb_ee_sex.Text = Reader["ee_sex"].ToString();
                }
                gv_WorkHistory.PageSize = Convert.ToInt32(ddl_PageSize.SelectedValue.ToString());
            }
            catch (Exception ex)
            {
                lb_acctSeachError.Text = "The Account Number entered was not found." + ex;
            }
            finally
            {

            }


        }
        protected void btn_adminMemberLookup_Click(object sender, EventArgs e)
        {
            //var tb_adminMemberLookup = (TextBox)lv_AdminSearch.FindControl("tb_adminMemberLookup");
            bool validSearch = false;
            switch (rbl_Search.SelectedValue.ToUpper())
            {
                case "S":
                    if (tb_adminMemberLookup.Text.Length >= 9)
                    {
                        Session["SSN"] = tb_adminMemberLookup.Text.Substring(0, 9);
                        validSearch = true;
                    }
                    break;
                default:
                    string[] results = tb_adminMemberLookup.Text.Split('-');
                    if (results.Length == 2)
                    {
                        Session["acct"] = results[1].Trim();
                        validSearch = true;
                    }
                    break;
            }
            if (validSearch)
            {
            }

            //Session["acct"] = tb_adminMemberLookup.Text;
            memberDataGet(Session["acct"].ToString(), "ZZ", Session["unlc"].ToString());
        }
    }
}

Open in new window

ASP.NETAJAXScripting Languages

Avatar of undefined
Last Comment
Shade22

8/22/2022 - Mon
guru_sami

- What is the default page set in your web.config after you login?
- Is your dashboard page protected by some roles?
ASKER
Shade22

After you log in you should go to dashboard.aspx.
Below is my web.config file

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<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=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>

  <connectionStrings>
    <add name="MyWebsite" connectionString="Data Source=111.111.11.11;Initial Catalog=MyWebsite;Persist Security Info=True;User ID=myuserID;Password=friedRioce" providerName="System.Data.SqlClient"/>    
  </connectionStrings>
  <appSettings>
    <add key="TrustPath" value="\\\\111.111.11.222\\c\\files\\"/>
        
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms loginUrl="default.aspx" timeout="2880" slidingExpiration="true" />
    </authentication>
      <authorization>
          <deny users="?" />
      </authorization>
    <profile defaultProvider="DefaultProfileProvider">
      <providers>
        <add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=55lkj323kj2k12j" connectionStringName="F61_Web_ConnectionString" applicationName="/" />
      </providers>
    </profile>
    <roleManager enabled="true" cacheRolesInCookie="true">
      <providers>
        <remove name="AspNetSqlRoleProvider"/>
        <add connectionStringName="MyWebsite" applicationName="MyWebsite-UserRoles"
        name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
        <add applicationName="/" name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=df544654df4454dfc" />
      </providers>
    </roleManager>
    <membership defaultProvider="MyWebsite">
      <providers>
        <add connectionStringName="MyWebsite" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" applicationName="MyWebsite" requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="5" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordStrengthRegularExpression="" name="MyWebsite" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=bd454gfeer54w456" />

      </providers>

    </membership>
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3326f385dfde35" connectionStringName="MyWebsite" />
      </providers>
    </sessionState>
  </system.web>

    <location path="userCreate.aspx">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>
    <!--<location path="default.aspx">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>-->
    <location path="passwordRecovery.aspx">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>
    <location path="css">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>
    <location path="images">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>
    <location path="disclaimer.html">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>
    <location path="pdf">
        <system.web>
            <authorization>
                <allow users="*" />

            </authorization>

        </system.web>

    </location>



    <system.webServer>
    <modules runAllManagedModulesForAllRequests="true" />
  </system.webServer>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
  </entityFramework>

</configuration>

Open in new window

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.
See how we're fighting big data
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
ASKER
Shade22

That didn't do anything.  Its almost as if I do log in, but then the membership boots me to the default.aspx page.
Your help has saved me hundreds of hours of internet surfing.
fblack61
guru_sami

Are you using built-in login control or a separted UI?
Can you share your login .aspx code.
ASKER
Shade22

I am using a Log in control.

Below is my MasterPage .aspx file
<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MyWebsite.master.cs" Inherits="MyWebsite.Mysite" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html>

<html lang="en">
  <head id="Head1" runat="server">
    <meta content="text" charset="utf-8">
    <title>MyWebsite</title>
          <asp:ContentPlaceHolder id="head" runat="server">

    </asp:ContentPlaceHolder>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

    <!-- Le styles -->
    <link href="css/styles.css" rel="stylesheet">

    <link href="css/styles2.css" rel="stylesheet">


      <style type="text/css">
          .auto-style1
          {
              width: 50px;
              float:right;
              padding:0 40px;
          }
          .auto-style2
          {
              width: 100px;
          }

      </style>


  </head>

  <body onLoad="goforit()">
     
          <form id="fi_MyWebsite" runat="server">
              <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
                            <div class="navbar">        
                                 <div class="navbar-inner">
                                     <table width="100%" border="0" >
  <tr>
    <td><img src="Images/my_logo.png" style="max-width:90%;float:left;padding-bottom:10px;" />   </td>
    <td align="right">
<asp:Login ID="log_Master" runat="server" BorderColor="#E6E2D8" BorderPadding="0" BorderStyle="Solid" BorderWidth="0px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" CssClass="loginarea" VisibleWhenLoggedIn="False" OnAuthenticate="Login1_Authenticate" DestinationPageUrl="~/dashboard.aspx" Height="181px">
                                        <InstructionTextStyle Font-Italic="True" ForeColor="Black" />
                                       
                                         <LayoutTemplate>
        <table width="100%" height="120px"  border="0">
  <tr>
    <td class="auto-style1" valign="top"><asp:Label ID="lb_UserName" runat="server" AssociatedControlID="UserName" ForeColor="#ffffff">Email:</asp:Label></td>
    <td><asp:TextBox ID="UserName" runat="server" Font-Size="1.5em"></asp:TextBox>
        <asp:TextBoxWatermarkExtender ID="wm_UserName" runat="server" WatermarkCssClass="watermark" TargetControlID="UserName" WatermarkText="e-mail@domain.com"></asp:TextBoxWatermarkExtender>
        <asp:RegularExpressionValidator ID="rev_Email" runat="server" ErrorMessage="<br />Invalid Email Address." ForeColor="#ffffff" ControlToValidate="UserName" ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" Display="Dynamic"></asp:RegularExpressionValidator>
        <asp:RequiredFieldValidator ID="rfv_Email2" runat="server" ControlToValidate="UserName" ErrorMessage="<br/>Email Address is required." ForeColor="#ffffff" ValidationGroup="ctl00$Login1" Display="Dynamic"></asp:RequiredFieldValidator></td>
      </tr>
  <tr>
    <td class="auto-style1"><asp:Label ID="lb_Password" runat="server" AssociatedControlID="Password" ForeColor="#ffffff">Password:</asp:Label></td>
    <td><asp:TextBox ID="Password" runat="server" Font-Size="1.5em" TextMode="Password"></asp:TextBox>
       <%-- <asp:TextBoxWatermarkExtender ID="wm_Password" runat="server" WatermarkCssClass="watermak" TargetControlID="Password" WatermarkText="ie. - 123456789 or Doe, John" ViewStateMode="Inherit" Enabled="True"></asp:TextBoxWatermarkExtender>
        --%>    </td><td>            
		</td>
  </tr>
  <tr>
    <td colspan="3">
	<asp:RequiredFieldValidator ID="rfv_Password2" runat="server" ControlToValidate="Password" ErrorMessage="Password is Required.&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" ForeColor="#ffffff" ValidationGroup="ctl00$Login1"></asp:RequiredFieldValidator>	</td>
  </tr>
  <tr>
    <td colspan="3"><asp:Label ID="lb_loginError" runat="server" ForeColor="White"></asp:Label></td>
  </tr>
  <tr>
    <td><a href="passwordRecovery.aspx" style="color:#fff;">Forgot your password?</a></td>
    <td align="right" class="auto-style2"><asp:Button ID="btn_Login" runat="server" CommandName="Login" Text="Log In" align="right" ValidationGroup="ctl00$Login1" OnClick="LoginButton_Click" CssClass="mainbutton-style" /></td>
   

                                         <TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em" ForeColor="White" />
                                     
        </tr>
                                         </table>
                                           </LayoutTemplate>
    </asp:Login>
        </td>
          <td>
             <table style="float:right;">
                                        <tr><td colspan="2">&nbsp;</td></tr>
                                          <tr align="left"><td><asp:LoginName ID="lin_MasterUserName" runat="server" ForeColor="White" Font-Bold="true" />&nbsp;&nbsp;</td></tr>
                                         <tr><td align="center">
                                         <asp:LoginStatus ID="lis_MasterUserStatus" runat="server" LoginText="" LogoutPageUrl="~/Default.aspx" ForeColor="White" LogoutAction="Redirect" LogoutImageUrl="~/images/logout.png" /></td></tr>
                                         </table>   

</td>
  </tr>
</table>
                                       

                                           
                         
</div>
                                </div>

    <div>
        <asp:ContentPlaceHolder id="cph_Main" runat="server">

                   

                    </asp:ContentPlaceHolder>

    </div>
                                                                  
                                                                  

                                                                  
    </form>                         
                    <div class="MYSite-footer">
       
             
     
      </div>

  </body>      

</html>

Open in new window

guru_sami

You have OnAuthenticate event and Login_Click. I think that's causing some confusion.
Can you try removing OnClick="LoginButton_Click" from your Login button markup.
You can move the code in the click handler to OnAuthenticated accordingly.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
Shade22

I merged the "onClick" procedure with the onAuthentication procedure and continue to have the issue of logging in twice.  So, basically no change.
guru_sami

Some more stuff to try:
- Add the Login_LoggedIn event. Do a manual Response.Redirect("~/dashboard.aspx") in there
-Set a breakpoint in the handler to see if the code is executed.
- Add a breakpoint in the  Page load of dashboard.aspx.cs. Check if you hit that on first login attempt or not.

- What is the url in the addressbar after your first login attempt?
- Do you have any other type of authorization set in code anywhere else?
ASKER
Shade22

Could it possibly have something to do with my IIS?  I don't get that issue, when I log in from the default.aspx page, but when I log in from ie. www.mywebsite.com it will make me log in twice.  So to make it work, I would have to go to www.mywebsite.com/default.aspx.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
guru_sami

So is it working fine with firefox or other browser?
What ASP.NET version are you using? Is any kind of Routing involved?
ASKER
Shade22

Its working fine with all the browsers, but the same issue happens to all browsers.
Our framework is 4.0.
guru_sami

You might want to do an explicit redirect from the page load of your Default page like:
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
    Response.Redirect(FormsAuthentication.DefaultUrl);
}

Open in new window

Here's the reference.

Or you can try setting the DefaultDocument in the IIS to dashboard.aspx and that might force to have ReturnUrl=dashboard.aspx attached to your default page when your first load the site.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
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.
ASKER
Shade22

Because it was the solution.