【问题标题】:How to check if old password matches before change it?如何在更改之前检查旧密码是否匹配?
【发布时间】:2015-01-16 16:48:31
【问题描述】:

我有这个代码:

//Update login query
string sql = "ALTER LOGIN " + login.ToUpper() + " WITH PASSWORD = '" + password + "' OLD_PASSWORD = '" + oldpassword + "'";

//Try connection and execute
using (SqlConnection connection = new SqlConnection(GetConnection()))
{
     connection.Open();

     SqlCommand command = new SqlCommand(sql, connection);
     command.CommandType = System.Data.CommandType.Text;
     var result = command.ExecuteScalar();
     connection.Close();
}

此 sql 查询更改数据库中的登录密码。请注意,它需要旧密码才能继续。不过,如果我传递了错误的旧密码,那么它会引发 SQLException:

无法更改登录“SEVA”,因为它不存在或您没有权限。

在执行此查询之前如何检查旧密码是否正确,以便向用户显示错误消息?

【问题讨论】:

  • 我不认为你可以。您可以做的最好的事情是尝试更改您已经完成的密码,然后捕获异常并在失败时向用户报告。
  • 为什么要在查询前检查?您知道异常是什么,只需根据抛出的成功或异常进行操作即可。
  • 查看以前的 Stackoverflow 帖子并在此处查看接受的答案 - stackoverflow.com/questions/19308801/… || stackoverflow.com/questions/26256351/…
  • @MethodMan 这是一个不同的问题。这里我们讨论的是 Sql Server 用户登录和他们的密码
  • Sorry Steve.. 听起来很相似.. 实际上他可以实现类似检查哈希是否在 sql 端完全匹配.. 然后在代码中如果它通过.. 然后接受新密码并使用它来更新数据库..我使用 SHA 加密来散列密码..

标签: c# sql .net ado.net


【解决方案1】:

试试这个。你需要在 catch 中添加一些东西来告诉用户他没有输入正确的密码

        //Update login query
        string sql = "ALTER LOGIN " + login.ToUpper() + " WITH PASSWORD = '" + password + "' OLD_PASSWORD = '" + oldpassword + "'";

        try {
        //Try connection and execute
        using (SqlConnection connection = new SqlConnection(GetConnection()))
        {
             connection.Open();

             SqlCommand command = new SqlCommand(sql, connection);
             command.CommandType = System.Data.CommandType.Text;
             var result = command.ExecuteScalar();
             connection.Close();
        }
    }
    catch(SQLException)
    {
//Do something here to tell the user something went wrong
    }

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2017-04-16
    • 1970-01-01
    相关资源
    最近更新 更多