我可以为用户创建一个SQL登录账号如下:检查SQL登录的凭证
CREATE LOGIN [myusername] WITH PASSWORD = N'mypassword', CHECK_POLICY= OFF;
,我可以检查如如果“名为myUsername”存在:
SELECT * FROM sys.server_principals WHERE name = N'myusername'
但我怎么能检查是否“名为myusername”和密码“wrong_password”由用户提供的是正确的?
我在C#中的解决方案是与罗杰的帮助如下:
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
}
}
如果他们不是,用户将无法登陆。你的意思是“我如何验证未登录的用户”?因为如果这是你的问题,你可能正在解决错误的问题 - 你想达到什么目的?你是否需要代表用户做些什么,或许? –
它看起来像[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。为什么你想要手动检查它? SQL服务器相当不错,它自己检查身份验证 - 所以你试图达到什么目的? –
您的每个用户是否都有SQL登录名?这不一定是非常常见的用法。它往往是要么映射域帐户,要么你有一个单一的SQL登录,并且你使用单独的用户表通过你的应用程序代码管理用户登录。 – Paddy