代码改变世界

对本地计算机上的 Windows 用户进行身份验证

2009-02-09 14:54  Scott Wong  阅读(1302)  评论(0编辑  收藏  举报

如果要对本地计算机上的 Windows 用户进行身份验证,可以在程序中使用 LogonUser 函数。有关 LogonUser 函数的说明请查阅 ms-help://MS.MSDNQTR.v90.chs/secauthn/security/logonuser.htm

 

下面的代码演示了如何在 C# 程序中调用 LogonUser 函数对 Windows 用户进行身份验证。

namespace ConsoleApplication1
{
    class Program
    {
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_PROVIDER_DEFAULT = 0;

        [DllImport("advapi32.dll", CharSet = CharSet.Auto)]
        public static extern int LogonUser(string lpszUserName, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        static bool Authenticate(string username, string password)
        {
            IntPtr token = IntPtr.Zero;

            bool isAuthenticated = (LogonUser(username, ".", password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref token) != 0);

            return isAuthenticated;
        }

        static void Main(string[] args)
        {
            if (args.Length == 2)
            {
                string username = "Administrator";
                string password = "";

                if (Authenticate(username, password))
                {
                    Console.WriteLine(string.Format("用户 {0} 已经通过身份验证。"));
                }
                else
                {
                    Console.WriteLine(string.Format("用户 {0} 未能通过身份验证。"));
                }
            }
            Console.Read();
        }
    }
}

 

执行效果如下:

image