简体   繁体   English

尝试创建登录页面,但用户名与密码不匹配 [学习目的]

[英]Trying to create a login page but it doesn't match username against password [Learning purpose]

If user puts any username or password from the database it logs in. It doesn't crossmatch between the index of them.如果用户从它登录的数据库中输入任何用户名或密码。它们的索引之间不会交叉匹配。 I'm working on this as a beginner learner.作为初学者,我正在研究这个。

if(txtusername.Text != null && txtpassword.Text != string.Empty)
{
    sql = string.Format(@" select * from idpass where username ='{0}' ", txtusername.Text );
    DataTable dtForNameAndRole = LoadDataByQuery(sql); 
    if(dtForNameAndRole.Rows.Count > 0)
    {

        sql = string.Format(@" select * from idpass where password ='{0}' ", txtpassword.Text);
        DataTable dtForNameAndRole2 = LoadDataByQuery(sql);
        if (dtForNameAndRole2.Rows.Count > 0)
        {
            sql = string.Format(@" select * from idpass where username = '{0}' and password ='{0}' ", txtusername.Text, txtpassword.Text);
            DataTable dtForNameAndRole3 = LoadDataByQuery(sql);
         
            Response.Redirect("Dashboard.aspx");
        }
        else
        {
            lblMessage.Text = "No Such Password";
        }
    }//end of if
    else
    {
        lblMessage.Text = "no such user";
    }
}
else
{

    msgtr.Visible = true;
    lblMessage.Text = "Sorry! Invalid user name or password.";
    lblMessage.ForeColor = Color.Red;
    return;
}

There are lot of issues in your existing code.您现有的代码中有很多问题。

  1. You should not store the plain password in the database.您不应将纯密码存储在数据库中。
  2. There is no need of calling the query 3 times.无需调用 3 次查询。 Only one time is sufficient.一次就足够了。
  3. You should not query only on password because passwords can be same for many users.您不应该只查询密码,因为许多用户的密码可能相同。
  4. Don't use * in the select query.不要在 select 查询中使用* You should use the columns as aliases.您应该使用这些列作为别名。
  5. Put the breakpoint and debug your code to see what is the query you're calling.放置断点并调试您的代码以查看您正在调用的查询是什么。 This way you will get to know whether your query is correct or not.通过这种方式,您将了解您的查询是否正确。 And you can run this query in the database as well to check whether it's working as expected or not.您也可以在数据库中运行此查询,以检查它是否按预期工作。

as noted, this is for learning.如前所述,这是为了学习。 However, VERY important to realize that you want to use the "built in system" for logons.但是,意识到您想使用“内置系统”进行登录非常重要。 The reasons are too long for this post.这个帖子的原因太长了。 But by using the defined built in logon system?但是通过使用定义的内置登录系统?

Then you can use the pre-made templates for logons.然后,您可以使用预先制作的模板进行登录。

You can setup security using IIS (internet services), and NOT have to hand code out a WHOLE web based security system.您可以使用 IIS(互联网服务)设置安全性,而不必编写整个基于 web 的安全系统。 This will save I can figure about a whole month of solid work.这将节省我大约整整一个月的扎实工作。 And if you use the built in logon system?如果您使用内置的登录系统?

Then you can even drop into a page the asp.net logon control - and it will do all the magic and coding for you - in other words, there is a HUGE system working behind the scenes to manage security and logons for you.然后,您甚至可以将 asp.net 登录控件放入页面 - 它会为您完成所有魔法和编码 - 换句话说,有一个庞大的系统在幕后为您管理安全和登录。 In a nutshell?简而言之?

Don't try and roll your own security system and logon system - it is FAR too much work.不要尝试推出自己的安全系统和登录系统——这工作量太大了。

Ok, now that I outlined the above, we are of course still here to learn.好的,既然我概述了上述内容,我们当然仍然在这里学习。 So, lets fix up your code you have.所以,让我们修复你的代码。

So, first up, I assume that you gone project->(your project properties), and under settings have setup a connection string (don't type those in manually - set that up in settings so you don't have to code out connection strings in code. You want ONE common connecting setting, since then you have one place to change this when you get around to publishing to a actual web site.所以,首先,我假设你去了项目->(你的项目属性),并且在设置下设置了一个连接字符串(不要手动输入这些 - 在设置中设置它,这样你就不必编码了代码中的连接字符串。您需要一个通用的连接设置,从那时起,当您开始发布到实际的 web 站点时,您可以在一个地方进行更改。

That setting is the ones you will find here:该设置是您可以在此处找到的设置:

在此处输入图像描述

Ok, now our code.好的,现在我们的代码。 Like everyone, it gets a bit tiring to wear out a few keyboards ever time we need to pull some data.像每个人一样,每当我们需要提取一些数据时,磨损几个键盘会有点累。 And eventually, you want to consider a data framework like EF (entity framework) to class out and "abstract" your data base operations.最终,您需要考虑一个数据框架,如 EF(实体框架)到 class 并“抽象”您的数据库操作。

However, when starting out - I think it is GREAT idea to try + test and play with some basic and simple database operations - such as your example sql queries.但是,在开始时 - 我认为尝试 + 测试和玩一些基本和简单的数据库操作是个好主意 - 例如您的示例 sql 查询。

So, first up, lets build that save world poverty's and the keyboards (so we don't have to re-code over and over some simple SQL queries)所以,首先,让我们构建拯救世界贫困和键盘的东西(所以我们不必一遍又一遍地重新编码一些简单的 SQL 查询)

So, lets drop in this code:所以,让我们加入这段代码:

    DataTable LoadDataByQuery(SqlCommand cmdSQL)
    {
        DataTable rstData = new DataTable();
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            cmdSQL.Connection = conn;
            conn.Open();
            rstData.Load(cmdSQL.ExecuteReader());
        }
        return rstData;
    }

So, now your code can become this:所以,现在你的代码可以变成这样:

As pointed out we CAN NOT and NEVER just check password alone, since many people might have the same password.正如所指出的,我们不能也永远不能只检查密码,因为很多人可能有相同的密码。

So we can check for user - or give message所以我们可以检查用户 - 或发送消息

Or THEN check for user + password - and give bad password message.或者然后检查用户+密码 - 并给出错误的密码信息。

Also, try to code without such a lot of nesting - its hard to debug and hard to follow.此外,尝试在没有这么多嵌套的情况下编写代码——它很难调试,也很难遵循。 I tend to like reverse the conditions, and BAIL OUT of the code when things go wrong and then keep going if code is ok.我倾向于反转条件,并且当 go 错误时退出代码,然后如果代码正常则继续。 That way you remove a boatload of nested if /else.这样你就可以删除一大堆嵌套的 if /else。

Try this code:试试这个代码:

       if (txtusername.Text == string.Empty)
        {
            msgtr.Visible = true;
            lblMessage.Text = "Please enter a user name";
            return;
        }
        // check/get user
        SqlCommand sql = new SqlCommand();
        sql.CommandText = @" select * from idpass where username = @user";
        sql.Parameters.Add("@user", SqlDbType.NVarChar).Value = txtusername.Text;
        DataTable dtForNameAndRole = LoadDataByQuery(sql);

        if (dtForNameAndRole.Rows.Count == 0)
        {
            msgtr.Visible = true;
            lblMessage.Text = "no such user";
            return;
        }

        // if we get this far, then user name = ok
        // user ok, try for pass word
        sql.CommandText += " AND password = @Pass";
        sql.Parameters.Add("@Pass", SqlDbType.NVarChar).Value = txtpassword.Text;
        DataTable dtForNameAndRole2 = LoadDataByQuery(sql);

        if (dtForNameAndRole2.Rows.Count == 0)
        {
            msgtr.Visible = true;
            lblMessage.Text = "Sorry! Invalid user password";
            lblMessage.ForeColor = Color.Red;
            return;
        }
        //get this far, user + password = ok
        Response.Redirect("Dashboard.aspx");
    }

Note also how our human minds work.还要注意我们人类的思想是如何工作的。 For example, we read this post on SO?例如,我们在 SO? you read from top to bottom - and your brain is thus wired to work this way.您从上到下阅读-因此,您的大脑以这种方式工作。

As a result, note how easy the above code is not only to read, but follow.因此,请注意上面的代码不仅易于阅读,而且易于遵循。

Hum, check for user name?嗯,检查用户名? no good, setup message - exit - we are done!!不好,设置消息 - 退出 - 我们完成了!

If user ok, hey, lets keep working our way though this problem - lets try user + password?如果用户没问题,嘿,让我们继续解决这个问题 - 让我们试试用户 + 密码? no good, setup message - exit - we are done!不好,设置消息 - 退出 - 我们完成了!

Hey, if we get this far?嘿,如果我们走到这一步? then we are done!!!那么我们就完成了!

Give the above approach a try - I think you like this idea and style.试试上面的方法——我想你喜欢这个想法和风格。

Note also, while we DID chew up about 2 extra lines of code to setup parameters?另请注意,虽然我们确实咀嚼了大约 2 行额外的代码来设置参数?

Those parameters are sql injection safe.这些参数是 sql 注入安全的。 We were able to "additive" to the sql and the parameters (thus saving even more code).我们能够“添加”到 sql 和参数(从而节省更多代码)。

We did not have to worry about single quotes - again string concatenations are error prone.我们不必担心单引号 - 字符串连接再次容易出错。

So my lesson and point?所以我的教训和观点? We used parameters NOT ONLY to prevent sql injection, but we in fact wound up with again more readable and maintainable code, and did not have to mess with string concatenate into the sql (well, ok, we did some concatenation - but NOT with a messy mix of single and double quotes).我们使用参数不仅是为了防止 sql 注入,而且实际上我们再次获得了更具可读性和可维护性的代码,并且不必将字符串连接到 sql (好吧,好吧,我们做了一些连接 - 但不是单引号和双引号的混乱组合)。 I point this out, since not only did we gain sql injection code, but the efforts to write the code was ALSO less.我指出这一点,因为我们不仅获得了 sql 注入代码,而且编写代码的努力也更少了。 I never liked people just banging the drum to not use sql concatenate strings based on user input - but ALSO one should then at least provide a coding approach that reduces the pain and suffering for having suggested code to prevent sql injection.我从不喜欢人们只是敲打鼓而不使用基于用户输入的 sql 连接字符串 - 但也应该至少提供一种编码方法,以减少建议代码以防止 sql 注入的痛苦和痛苦。

I often use the above EVEN WHEN there is no chance of sql injection, since you can even on the fly add to the sql, and as above shows, on the fly even build up and add more parameters as we did above.即使没有 sql 注入的机会,我也经常使用上述方法,因为您甚至可以在运行中添加到 sql,如上所示,在运行中甚至可以像我们上面所做的那样构建并添加更多参数。

Good luck - all the best in the new year.祝你好运——新的一年万事如意。

public DataSet Login() {公共数据集登录(){

        names.Add("@ID"); types.Add(SqlDbType.VarChar); values.Add(RegistrationID);
        names.Add("@Password"); types.Add(SqlDbType.VarChar); values.Add(password);
        return DAobj.GetDataSet(SP_LoginAuthentication, values, names, types);
    }

create proc SP_LoginAuthentication @ID varchar(50), @Password varchar(50) as begin select * from TableName where id=@ID and Password=@Password And IsActive=1 end create proc SP_LoginAuthentication @ID varchar(50), @Password varchar(50) as begin select * from TableName where id=@ID and Password=@Password And IsActive=1 end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试创建一个登录页面,如果用户名正确,它还会显示“只有密码错误” - Trying to create a Login page where it also shows that "Only password is wrong" if username is correct 输入正确的用户名和密码后,ASP登录无法正常工作 - ASP login doesn't work when correct username and password are entered 以编程方式将用户名和密码发布到登录页面 - Post Username and Password to login page programmatically 使用数据库中的用户名和密码登录页面无法正常工作,看不到原因 - Login page using username and password from database not fully working, can't see why 尝试使用StreamWriter和StreamReader创建登录系统,但是不起作用? - Trying to use StreamWriter and StreamReader to create a login system but it doesn't work? C#使用Windows应用程序将用户名/密码发布到登录页面 - C# post username/password to the login page using windows application 针对AD异常验证用户名和密码 - Validate a username and password against AD exception 针对 Active Directory 验证用户名和密码? - Validate a username and password against Active Directory? 我们可以构建自定义登录页面以将用户名和密码发送到 AD FS 2016 而不是使用 OOB 页面吗 - Can we build a custom login page to send the username and password to AD FS 2016 instead of using the OOB page 我正在尝试将用户名/密码登录系统写入文本文件,并且不确定如何修复一些错误 - I am trying to write to a text file a username/password login system and am uncertain how to fix a few errors
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM