繁体   English   中英

以登录形式创建Windows身份验证和SQL Server身份验证

[英]Creating Windows authentication and SQL Server authentication in login form

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

https://i.stack.imgur.com/uziUD.png

我的目标是允许用户选择是使用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!");    
    }
}

我已经使用示例项目验证了该代码是否有效。 您只需要确保以下几点:

  1. 用户名和密码正确(服务器>安全性)。
  2. 用户有权访问GCVS2_DEV_GHR表。 可以在(服务器>安全性>用户)下进行配置

同样,这种编码方式也不是一种好的方法,但是由于您对C#似乎并不陌生,因此请确保对更多的良好实践进行研究。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM