检查 SQL 登录的凭据

ber*_*ter 2 c# sql sql-server

我可以为用户创建一个 SQL 登录帐户,如下所示:

CREATE LOGIN [myusername] WITH PASSWORD = N'mypassword', CHECK_POLICY= OFF;
Run Code Online (Sandbox Code Playgroud)

我可以检查例如“myusername”是否存在:

SELECT * FROM sys.server_principals WHERE name = N'myusername'
Run Code Online (Sandbox Code Playgroud)

但是如何检查用户提供的“myusername”和密码“wrong_password”是否正确?

我的 C# 解决方案是在 Roger 的帮助下,如下所示:

    private static bool SqlLoginExists(string username)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = "Data Source=.;" + "Integrated Security=SSPI;";
        connection.Open();

        string sql_command = "SELECT count(*) FROM sys.server_principals WHERE name = N'" + username + "'";

        using (SqlCommand command = new SqlCommand(sql_command, connection))
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    if (reader.GetValue(0).ToString() == "1")
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public static bool CheckSQLCredentialsIfLoginExists(string username, string password)
    {
        bool SqlUserExists = SqlLoginExists(username);

        if (SqlUserExists)
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = "Data Source=.;" + "User id=" + username+";Password=" + password +";";
            try
            {
                connection.Open();
                return true;
            }
            catch (SqlException ex)
            {
                connection.Dispose();
                return false;
            }

        }
        else
        {
            return true; // it is not a problem for me if account does not exist (as it will be created later), I am only worried about the case when the credentials are wrong
        }
    }
Run Code Online (Sandbox Code Playgroud)

Rog*_*olf 5

您可以使用该pwdcompare()功能:

select pwdcompare(N'MyWrongPassword', sl.password_hash) as [Match]
from master.sys.sql_logins sl
where sl.name = N'MyLogin';
Run Code Online (Sandbox Code Playgroud)

但是,您很有可能朝着错误的方向工作 - 尝试使用提供的凭据建立连接更为正确。