C# 在登录表单中创建Windows身份验证和SQL Server身份验证

C# 在登录表单中创建Windows身份验证和SQL Server身份验证,c#,sql,sql-server,authentication,ssms,C#,Sql,Sql Server,Authentication,Ssms,我在Visual Studio C#中有一个登录表单,下面是它的屏幕截图 我的目标是允许用户选择是使用Windows身份验证登录,在工作场所使用LAN网络还是使用SQL Server身份验证(用户名和密码存储在服务器->安全->登录中) 以下是迄今为止的代码: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing;

我在Visual Studio C#中有一个登录表单,下面是它的屏幕截图

我的目标是允许用户选择是使用Windows身份验证登录,在工作场所使用LAN网络还是使用SQL Server身份验证(用户名和密码存储在服务器->安全->登录中)

以下是迄今为止的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Data.OleDb;

namespace Login_HouseKeeping_
{
    public partial class Form1: Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // Connection string
        string cs = @"Data Source = 172.28.40.19\CASINO2008R2; Initial catalog =GCVS2_DEV_GHR; Integrated Security = True;";

        // Login click event
        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox2.Text == "")
            {
                MessageBox.Show("Please provide Username and Password");
                return;
            }
            else
                try
                {
                    //Create sqlconnection
                    SqlConnection con = new SqlConnection(cs);

                    SqlCommand cmd = new SqlCommand(@"SELECT * FROM Logins WHERE Username = @username AND Password = @Password", con);

                    cmd.Parameters.AddWithValue("@username", textBox1.Text);
                    cmd.Parameters.AddWithValue("@Password", textBox2.Text);

                    con.Open();

                    SqlDataAdapter adapt = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    adapt.Fill(ds);

                    con.Close();

                    int count = ds.Tables[0].Rows.Count;

                    // if count equals to 1, then show frmMain form
                    if (count == 1)
                    {
                        MessageBox.Show("Login successful");
                        this.Hide();

                        frmMain fm = new frmMain();
                        fm.Show();
                    }
                    else
                    {
                         MessageBox.Show("Login failed");
                    }
               }
               catch (Exception ex)
               {
                   MessageBox.Show(ex.Message);
               }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            textBox2.PasswordChar = '*';
        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}
我似乎找不到太多关于在我的登录中实现这两种身份验证的资源。我如何做到这一点

编辑:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void btn_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_Login_Click(object sender, EventArgs e)
        {



            var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
            connStrBldr.DataSource = "172.28.40.19\CASINO2008R2";
            connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";
            if (WindowsAuth)
            {
                connStrBldr.IntegratedSecurity = true;
            }
            else
            {
                connStrBldr.IntegratedSecurity = false;
                connStrBldr.UserID = textBox1.Text;
                connStrBldr.Password = textBox2.Text;
            }
            using (SqlConnection con = new SqlConnection(connStrBldr.ToString()))
            {
                con.Open();
                //do your lookup on login here
            }







        }

        private void WindowsAuth_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void SqlAuth_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}

身份验证由连接字符串控制。您最好使用
System.Data.SqlClient.SqlConnectionStringBuilder
根据您想要的是SQL Server身份验证还是Windows身份验证动态构建连接字符串:

var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
connStrBldr.DataSource = "172.28.40.19\CASINO2008R2";
connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";
if (useWindowsAuth) {
    connStrBldr.IntegratedSecurity = true;
} else {
    connStrBldr.IntegratedSecurity = false;
    connStrBldr.UserID = textBox1.Text;
    connStrBldr.Password = textBox2.Text;
}
using (SqlConnection con = new SqlConnection(connStrBldr.ToString())) {
    con.Open();
    //do your lookup on login here
}

我之所以发布这个答案,是因为OP似乎无法让@Tim的答案起作用。归功于@Tim

只要简单地使用:

编辑:已更改,因为windows身份验证不强制使用用户名和密码

private void btn_Login_Click(object sender, EventArgs e)
{
    bool useWindowsAuth = WindowsAuth.Checked; // Assuming that WindowsAuth is your radio button

    string userName = string.Empty;
    string password = string.Empty;

    if(!useWindowsAuth)
    {
        userName = textBox1.Text;
        password = textBox2.Text;

        if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
        {
            MessageBox.Show("Please provide Username and Password");
            return;
        }
    }

    var connStrBldr = new System.Data.SqlClient.SqlConnectionStringBuilder();
    connStrBldr.DataSource = @"172.28.40.19\CASINO2008R2";
    connStrBldr.InitialCatalog = "GCVS2_DEV_GHR";

    if (useWindowsAuth) 
    {
        connStrBldr.IntegratedSecurity = true;
    } 
    else 
    {
        connStrBldr.IntegratedSecurity = false;
        connStrBldr.UserID = userName;
        connStrBldr.Password = password;
    }

    bool validUser = true;

    try
    {
        using (SqlConnection con = new SqlConnection(connStrBldr.ToString())) 
        {
            con.Open();
            //do your lookup on login here
        }
    }
    catch(SqlException) // An exception will be caught if invalid credentials were used.
    {
        validUser = false;
    }

    if(validUser)
        MessageBox.Show("Login successful!");
    else
        MessageBox.Show("Login failed!");    
    }
}
我已经用一个示例项目验证了代码的有效性。您只需确保以下几点:

  • 用户名和密码正确(服务器>安全性)
  • 用户可以访问
    GCVS2\u DEV\u GHR
    表。这可以在(服务器>安全性>用户)下配置

  • 而且,这种编码方式不是一种很好的方法,但因为您似乎对C#还不熟悉,所以请确保学习更多关于良好实践的知识。

    问题是什么?问题是我不知道如何在登录名中使用windows身份验证和sql server身份验证。active directory的windows身份验证?是的,我需要一直这样做吗将登录凭据引用到我自己的数据库?这样做的目的是允许用户选择windows身份验证并使用其凭据继续登录,或选择sql server身份验证并使用存储在sql server上的凭据登录?如果用户希望使用另一个用户的凭据执行windows身份验证(Active Directory),该怎么办?这种方法是否将您的凭据限制为当前登录用户的凭据?当您设置
    IntegratedSecurity=false
    时,这意味着它将使用SQL Server的身份验证,该身份验证完全由SQL Server处理,而不是由您的
    登录
    表维护。使用
    CREATE LOGIN
    管理SQL Server身份验证的登录。@John Ephraim Tugado,要作为另一个用户进行windows身份验证,必须首先通过调用windows api为您的进程模拟另一个用户。我的示例仅说明了如何根据运行时选择使用windows auth或sql auth进行动态连接。我已经在sql server中进行了登录。在“if(useWindowsAuth)”下,该约定指的是什么?您的意思是它可以在您的计算机上工作吗?您可以使用两种身份验证模式登录?好的,我尝试了您的代码,但我有一个问题,如果我想通过windows身份验证登录,我必须输入用户名和密码并登录,还是将其保留为空?保留为空。不需要它,因为
    IntegratedSecurity
    设置为
    true
    我将您的答案标记为已解决。我可以使用我已经创建的sql登录中的凭据通过sql auth登录。我还需要在登录时进行查找吗?我很困惑,不需要查看登录名。只要您能够打开
    SqlConnection
    ,就意味着用户是有效的。