使用Win32API LogonUser 在C#程序中进行域认证

来源:互联网 发布:淘宝分销钱怎么分 编辑:程序博客网 时间:2024/06/05 16:49

使用C#的用户在编写的WinForm程序中,如果需要使用域账号进行认证管理一般需使用Win32API LogonUser()进行。

这里提供一段我使用的完整的验证代码,大家可以根据需要自己进行适当的修改从而实现在WinForm中。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;    //DllImport

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


        
private void button1_Click(object sender, EventArgs e)
        
{
            
const int LOGON32_LOGON_INTERACTIVE = 2//通过网络验证账户合法性 
            const int LOGON32_PROVIDER_DEFAULT = 0//使用默认的Windows 2000/NT NTLM验证方式            
            IntPtr tokenHandle = new IntPtr(0);
            tokenHandle 
= IntPtr.Zero;
            
/*
             * textBox2.Text 域 如:officedomain
             * textBox1.Text 域帐号 如:administrator
             * textBox3.Text 密码 如:123456
             
*/

            
bool checkok = LogonUser(textBox2.Text, textBox1.Text, textBox3.Text, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
            
if(checkok)
            
{
                label1.Text 
= "欢迎 " + textBox2.Text + " Just YY it."
            }

            
else
            
{
                label1.Text 
= "LZ洗洗睡了";
            }

        }


        
//调用Win32API Import advapi32.dll
        [DllImport("advapi32.dll")]
        
//映射函数LogonUser
        private static extern bool LogonUser( string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
    }

}

 

参考资料:

如何验证 VisualBasic.NET 或 Visual Basic 2005 应用程序中 Windows 用户权限 http://support.microsoft.com/kb/841699/zh-cn

LogonUser Function http://msdn2.microsoft.com/en-us/library/aa378184.aspx