简体   繁体   English

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

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

I have a login form in Visual Studio C# and below is a screenshot of it. 我在Visual Studio C#中有一个登录表单,下面是它的屏幕截图。

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

My goal is to allow the user to choose whether to log in using Windows authentication, in a workplace as we are using LAN network or using SQL Server authentication (username and password are stored in server -> security -> login). 我的目标是允许用户选择是使用Windows身份验证,在我们正在使用LAN网络的工作场所还​​是使用SQL Server身份验证(用户名和密码存储在服务器->安全性->登录中)登录。

Below is the code so far: 下面是到目前为止的代码:

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();
        }
    }
}

I can't seem to find many resources on implementing these two authentication into my login. 我似乎找不到很多在登录中实现这两种身份验证的资源。 How do I achieve this? 我该如何实现?

EDIT: 编辑:

    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)
        {

        }
    }
}

Authentication is controlled by your connection string. 身份验证由您的连接字符串控制。 Your best bet is to use System.Data.SqlClient.SqlConnectionStringBuilder to build the connection string dynamically based on whether you want SQL Server auth or Windows auth: 最好的选择是使用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
}

I'm only posting this answer since OP can't seem to make @Tim's answer work. 我只是发布此答案,因为OP似乎无法使@Tim的答案起作用。 Credits to @Tim. 致谢@Tim。

Just simply use: 只需简单地使用:

EDIT: Changed since username and password is not mandatory for windows authentication. 编辑:更改,因为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!");    
    }
}

I have verified that the code works using a sample project. 我已经使用示例项目验证了该代码是否有效。 You just have to make sure of the following: 您只需要确保以下几点:

  1. Username and Password is correct (Server > Security). 用户名和密码正确(服务器>安全性)。
  2. User has access to GCVS2_DEV_GHR table. 用户有权访问GCVS2_DEV_GHR表。 This can be configured under (Server > Security > User) 可以在(服务器>安全性>用户)下进行配置

Also, this way of coding is not a good way to do it but since you seem new to C# just make sure to study more about good practices. 同样,这种编码方式也不是一种好的方法,但是由于您对C#似乎并不陌生,因此请确保对更多的良好实践进行研究。

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

相关问题 WPF登录身份验证表单SQL Server数据库 - WPF login authentication form SQL Server database Windows 身份验证到 Sql Server 身份验证 - Windows Authentication to Sql Server Authentication 登录信息sql windows身份验证 - login info sql windows authentication 使用Windows身份验证连接到SQL Server - Connect to SQL Server with windows authentication 如何检查登录程序是否支持Windows身份验证和sql身份验证模式? - How to check if login program supports windows authentication and sql authentication mode? Windows Blazor 服务器应用程序的身份验证 - 登录弹出窗口 - Windows Authentication for Blazor Server app - login popup EWS托管API和SQL Server-登录失败。 该登录名来自不受信任的域,不能与Windows身份验证一起使用 - EWS Managed API and SQL Server - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication Windows服务SQL Server Windows身份验证 - Windows Service SQL Server Windows Authentication 如何将SQL Server 2005从Windows身份验证更改为SQL身份验证? - How to change SQL Server 2005 from Windows Authentication to SQL Authentication? 从 SQL 服务器数据库登录认证 - Login Authentication from SQL Server database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM