0

I am currently creating a CMS and have a section where a user can create, edit and delete users. The information is generated from a database, where I have made a table with User_ID, User_Name and User_Password. This means I do not want to use the automatically generated database tables VS gives you for their log ins.

With this I am trying to develop a really basic log in but I am having trouble understanding the process.

This is my web.config for the whole application:

<?xml version="1.0"?>
<configuration>
  <connectionStrings>
    <add name="websiteContent" connectionString="uid=AAA;pwd=AAA;Initial Catalog=AAA;Data Source=.\SQLEXPRESS"/>
  </connectionStrings>
  <system.web>
    <compilation debug="true" targetFramework="4.0"/>
    <authentication mode="Forms">
      <forms loginUrl="~/tools/default.aspx" timeout="2880"/>
    </authentication>
  </system.web>
</configuration>

Web.config for login:

<?xml version="1.0"?>
<configuration>

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

  <system.web>
    <authorization>
      <deny users="?"/>
    </authorization>
  </system.web>

</configuration>

This is my log in on the front end:

            <asp:Login ID="Login1" runat="server" CssClass="loginSec" TextLayout="TextOnTop"
                TitleText="" OnAuthenticate="Login1_Authenticate">
                <LabelStyle CssClass="lblLogin" />
                <TextBoxStyle CssClass="txtLogin" />
            </asp:Login>

Log in from the back end:

protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
    string userName = Login1.UserName;
    string passWord = Login1.Password;
    bool rememberUserName = Login1.RememberMeSet;

    using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
    {
        sqlCon.Open();
        string SQL = "SELECT CMS_Username, CMS_Password FROM CMS_Users WHERE CMS_Username ='" + userName + "' AND CMS_Password ='" + passWord + "'";
        using (SqlCommand sqlComm = new SqlCommand(SQL, sqlCon))
        {
            sqlComm.ExecuteScalar();

            if (sqlComm.ExecuteScalar() != null)
            {
                Response.Redirect("cms.aspx");
            }
            else
            {
                Session["UserAuthentication"] = "";
            }
        }
        sqlCon.Close();
    }
}

What I have done so far has prevented access to the page cms.aspx, but the log in never redirects to the page.

Any insight would be appreciated!!

wilcode
  • 633
  • 2
  • 10
  • 25
  • Can you show your code in the cms.aspx to prevent the unauthorized access? – Khadim Ali May 05 '13 at 21:38
  • @Ali.NET I do not have any, I thought that was what the web.config was doing? – wilcode May 05 '13 at 21:46
  • @ispiro I get this in my URL - http://localhost:50412/ThirdYearProject/tools/default.aspx?ReturnUrl=%2fThirdYearProject%2ftools%2fcms.aspx. I presume I am not redirecting properly? – wilcode May 05 '13 at 21:49
  • 1
    Never store passwords. Only their hashes. http://stackoverflow.com/a/9458158/939213 – ispiro May 05 '13 at 21:49
  • Is the line `Response.Redirect("cms.aspx");` executed? (You can check that by putting a breakpoint on that line (or preferably the line before it) – ispiro May 05 '13 at 21:53
  • 1
    I think you have to remove the web.config part for the authorization as it is for use with built in login factility. And have to check authorization manually. Like checking the Session[""] variable for null or not. – Khadim Ali May 05 '13 at 21:54
  • @ispiro It doesn't get past that point, it just adds this to the end of the URL - default.aspx?ReturnUrl=%2fThirdYearProject%2ftools%2fcms.aspx – wilcode May 05 '13 at 21:58
  • @Ali.NET, that is the part which I am unsure of. My CMS only works from the cms.aspx page, so I need to add something to allow access from that user? – wilcode May 05 '13 at 22:00
  • I'm guessing you're using the default ASP.Net project template - I just checked, and perhaps the addition to the URL is done in the codebehind (-the C# code behind a web page) of the `Login.aspx` page. I hope that helps. I'm sorry I can't help more than that. Good luck! – ispiro May 05 '13 at 22:08
  • 1
    @lauw0203 As per my understanding, yes. you have to disable default security what you have mentioned in web.config (for login). And have to manually authenticate the user like if(Session["UserAuthentication"]==null) { response.redirect("Login.aspx")} – Khadim Ali May 05 '13 at 22:13
  • @Ali.NET This worked better, but I can go back to the log in page and access the cms.aspx without logging. Could this be that the session is still true? – wilcode May 05 '13 at 22:35
  • 2
    you really should change that sql to use parameters. By entering a username of simon'-- I could skip the password checking for the simon account. For more of a giggle, I could also send some delete commands to wipe your DB clean. NEVER use inline concatenation for SQL & as @ispiro said, hash your passwords. – Simon Halsey May 06 '13 at 00:26
  • 1
    @lauw0203 Most probably. IMO, your UserAuthentication session handling should be something like this. 1) Set the Session to, for e.g., UserName when authenticated from data source 2) Set the Session to Null in case of authentication falied 3) Check for Session variable shouldn't be null when the client access the cms.aspx page 4) Set the Session to null when log out. – Khadim Ali May 06 '13 at 06:49

1 Answers1

1

I have added the settings of Authenticated as required by the docs

Custom authentication schemes should set the Authenticated property to true to indicate that a user has been authenticated.

More research has led me to the neccessity to add this line in your code

FormsAuthentication.SetAuthCookie(Login1.UserName, true);

Also I will try to change your code in such a way that ExecuteScalar returns the count of user with that username and password. In this way ExecuteScalar will never return NULL, but a value that could be zero if no user exists or 1 if user exists (I suppose that you don't have two records with the same user and password)

using (SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["websiteContent"].ConnectionString))
{
    sqlCon.Open();
    string SQL = "SELECT COUNT(*) As LoginFound FROM CMS_Users " + 
                 "WHERE CMS_Username =@usr AND CMS_Password = @pwd";
    using (SqlCommand sqlComm = new SqlCommand(SQL, sqlCon))
    {
        sqlComm.Parameters.AddWithValue("@usr", userName);
        sqlComm.Parameters.AddWithValue("@pwd", password);
        int result = (int)sqlComm.ExecuteScalar();
        if (result > 0)
        {
            // In case of success you need to communicate this 
            e.Authenticated = Authenticated;
            FormsAuthentication.SetAuthCookie(Login1.UserName, true);
            Response.Redirect("~/tools/cms.aspx");
        }
        else
        {
            Session["UserAuthentication"] = "";
        }
    }
}

Also, I have removed the string concatenation from your sql command. This is the right way to pass string text to the database. Particularly if the values comes from your user input.

(See Sql Injection )

EDIT Of course the cmd.aspx page should check if the user has been authenticated because otherwise one could type directly the url of the cms.aspx page bypassing the login control.
So in the Page_Load event of cms.aspx add this code

protected void Page_Load(object sender, EventArgs e)
{
    if ( !Request.IsAuthenticated)
    {
        Response.Redirect("~/tools/default.aspx");
    }
}
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Thanks @Steve. In regards to the SQL, that was a temporary measure as I am using the default ASP.NET log in template and I am not sure what the login and password textbox default names are. Do you have any idea? – wilcode May 05 '13 at 21:41
  • Thank you for adding to your explanation. However, when I attempt to log in it returns to the same page? If I remove the web.config it works but I can then access the cms.aspx page without logging in? – wilcode May 05 '13 at 22:11
  • but the page cms.aspx is in the same folder with default.aspx (tools?) – Steve May 05 '13 at 22:12
  • Yes. Sorry if I am not understanding this very well! – wilcode May 05 '13 at 22:13
  • Then what happens if you specify exactly the path to redirect `~/tools/cms.aspx` – Steve May 05 '13 at 22:14
  • The CMS now logs in, but I can access it without logging in anyway? Unless that is because the authentication is still true? I have also tried a combination of the other answers given, removing the web.config and adding authentication to the cms.aspx page but there are still problems. – wilcode May 05 '13 at 22:30
  • In the Page_Load for the cms.aspx page add a check for IsAuthenticated. I will add to the answer to better explain with code – Steve May 05 '13 at 22:43