C#实现的WINDOWS登录功能示例
程序员文章站
2023-12-05 19:55:46
本文实例讲述了c#实现的windows登录功能。分享给大家供大家参考,具体如下:
using system;
using system.data;
using...
本文实例讲述了c#实现的windows登录功能。分享给大家供大家参考,具体如下:
using system; using system.data; using system.configuration; using system.collections; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.runtime.interopservices; using system.security.principal; namespace yutest { public partial class _default : system.web.ui.page { [dllimport("advapi32.dll", charset = charset.auto)] public static extern bool logonuser(string lpszusername,string lpszdomain,string lpszpassword,int dwlogontype,int dwlogonprovider,out int phtoken); protected void page_load(object sender, eventargs e) { string aaa = system.threading.thread.currentprincipal.identity.name; //string bbb = system.threading.thread.currentprincipal.identity.n; //system.environment.userdomainname //system.environment.username } protected void button1_click(object sender, system.eventargs e) { //验证用户的输入是否为空 if (tdomain.text.trim().length > 0 && tusername.text.trim().length > 0&& tpassword.text.trim().length > 0) { //调用函数login(string username, string password, string domain) //实现windows登录 if (login(tusername.text.trim(), tpassword.text.trim(),tdomain.text.trim()) == true) { //显示登录成功信息 loginmsg.text = "登录成功!!!"; loginmsg.visible = true; return; } else { //显示登录失败信息 loginmsg.text = "登录失败,请重新输入用户名称、密码及其系统域名!!!"; loginmsg.visible = true; } } } private bool login(string username, string password, string domain) { //获取用户名称和系统域名 string text1 = domain.trim(); string text2 = username.trim(); text2 = text2.replace("/", @"\"); //处理符号“/” int num1 = text2.indexof('\\'); //获取符号“\”的索引 if (num1 != -1) { //格式化用户名称和系统域名 text1 = text2.substring(0, num1); text2 = text2.substring(num1 + 1); } else { //格式化用户名称和系统域名 num1 = text2.indexof('@'); if (num1 != -1) { text1 = text2.substring(num1 + 1); text2 = text2.substring(0, num1); } } //调用函数authenticateuser()实现用户windows登录 return authenticateuser(text2, password.trim(), text1); } private bool authenticateuser(string username, string password,string domain) { //设置用户登录成功的标志 bool flag1 = false; try { int num1; intptr ptr1; //调用windows登录的api if (!logonuser(username, domain, password, 2, 0, out num1)) { //返回登录结果 return flag1; } //调用.net中的windows登录 ptr1 = new intptr(num1); windowsidentity identity1 = new windowsidentity(ptr1); windowsprincipal principal1 = new windowsprincipal(identity1); httpcontext.current.user = principal1; //设置系统cookie和重定向页面 formsauthentication.setauthcookie(principal1.identity.name, false); formsauthentication.redirectfromloginpage(username, false); flag1 = true; } catch (exception) { } return flag1; } } }
更多关于c#相关内容感兴趣的读者可查看本站专题:《c#常见控件用法教程》、《winform控件用法总结》、《c#程序设计之线程使用技巧总结》、《c#数据结构与算法教程》及《c#面向对象程序设计入门教程》
希望本文所述对大家c#程序设计有所帮助。