Window 模擬其他用戶操作 SQL Server

背景,需要在當前上下文中連接兩個數據庫,且兩個數據庫都需要使用不同的域賬號登錄。

首先注意到SqlConnection 對象有個重載的方法,但看了描述貌似不支持 Windows 集成身份驗證。

 

 經測試,確實不支持

那麼嘗試另外的方法,嘗試用C#代碼使用另外的用戶登錄,然後使用新用戶的上下文執行一些操作,完整代碼如下,需要使用管理員賬號執行。當然,該操作不僅限於連接數據庫

 

using Microsoft.Win32.SafeHandles;
using System;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace ConsoleApp2
{
    class Program
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
            int dwLogonType, int dwLogonProvider, out SafeAccessTokenHandle phToken);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        static void Main(string[] args)
        {
            //var conn = new SqlConnection();

            var userName = "xxxx";
            var password = "xxxxx";
            var domainName = "xxxxx";

            const int LOGON32_PROVIDER_DEFAULT = 0;
            //This parameter causes LogonUser to create a primary token.   
            const int LOGON32_LOGON_INTERACTIVE = 2;

            SafeAccessTokenHandle safeAccessTokenHandle;
            bool returnValue = LogonUser(userName, domainName, password,
                LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                out safeAccessTokenHandle);
            Console.WriteLine("模擬前:");
            Console.WriteLine("Current User:" + WindowsIdentity.GetCurrent().Name);
            WindowsIdentity.RunImpersonated(safeAccessTokenHandle,
                () =>
                {
                    Console.WriteLine("模擬中:");

                    Console.WriteLine("Current User:" + WindowsIdentity.GetCurrent().Name);
                    try
                    {
                        var conn = new SqlConnection("Server=remoteserver1;Database=DbName;Trusted_Connection=SSPI;"
                            );
                        conn.Open();

                        var cmd = new SqlCommand("select 1", conn);
                        Console.WriteLine(cmd.ExecuteScalar());

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                });

            Console.WriteLine("模擬後:");
            Console.WriteLine("Current User:" + WindowsIdentity.GetCurrent().Name);


        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章