通过LDAP验证Active Directory服务
服务 通过 验证 Directory ldap Active
2023-09-11 14:16:42 时间
原文地址:http://www.byywee.com/page/M0/S215/215725.html
C#:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.DirectoryServices; using System.Configuration; using System.Text.RegularExpressions; namespace ldapcs { class Program { static void Main(string[] args) { string path = "LDAP://192.168.137.210:389/ou=pet,dc=abc,dc=com "; string username = "uname"; string pwd = "upwd"; string domain = "abc.com"; LdapAuthentication ldap = new LdapAuthentication(path); Console.WriteLine( ldap.IsAuthenticated(domain, username, pwd)); Console.WriteLine(ldap.GetGroups()); } public class LdapAuthentication { private string _path; private string _filterAttribute; public LdapAuthentication(string path) { _path = path; } public bool IsAuthenticated(string domain, string username, string pwd) { string domainAndUsername = domain + @"\" + username; DirectoryEntry entry = new DirectoryEntry(_path, username, pwd); try { //Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (string)result.Properties["cn"][0]; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return true; } public string GetGroups() { DirectorySearcher search = new DirectorySearcher(_path); search.Filter = "(cn=" + _filterAttribute + ")"; //search.SearchRoot = "PET"; StringBuilder groupNames = new StringBuilder(); try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; string dn; int equalsIndex, commaIndex; for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++) { dn = (string)result.Properties["memberOf"][propertyCounter]; equalsIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalsIndex) { return null; } groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)); groupNames.Append("|"); } } catch (Exception ex) { throw new Exception("Error obtaining group names. " + ex.Message); } return groupNames.ToString(); } } /// <summary> /// 验证AD用户是否登录成功 /// </summary> /// <param name="domain"></param> /// <param name="userName"></param> /// <param name="password"></param> /// <returns></returns> public static bool TryAuthenticate(string domain, string userName, string password) { bool isLogin = false; try { DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), userName, password); entry.RefreshCache(); isLogin = true; } catch { isLogin = false; } return isLogin; } } }
Java:
import java.util.Hashtable; import java.util.Enumeration; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls ; import javax.naming.NamingEnumeration; import javax.naming.directory.SearchResult; public class LDAPtest { public static void main(String[] args) { LDAPtest ldap=new LDAPtest(); ldap.init(); } public void init(){ DirContext ctx = null; Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, "ldap://192.168.137.210:389/");//连接LDAP的URL和端口 //env.put(Context.SECURITY_AUTHENTICATION, "simple");//以simple方式发送 env.put(Context.SECURITY_PRINCIPAL, "cn=uname,ou=PET,DC=abc,DC=com");//用户名 env.put(Context.SECURITY_CREDENTIALS, "upwd");//密码 String baseDN="ou=PET,DC=abc,DC=com";//查询区域 String filter="(&(objectClass=person))";//条件查询 try{ ctx = new InitialDirContext(env);//连接LDAP服务器 System.out.println("Success"); SearchControls constraints = new SearchControls();//执行查询操作 constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); NamingEnumeration en=ctx.search(baseDN, filter, constraints); if(en==null){ System.out.println("There have no value"); }else{ while(en.hasMoreElements()){ Object obj=en.nextElement(); if(obj instanceof SearchResult){ SearchResult sr=(SearchResult) obj; String cn=sr.getName(); System.out.println("cccccc: "+cn); } } } }catch(javax.naming.AuthenticationException e){ System.out.println(e.getMessage()); }catch(Exception e){ System.out.println("erro:"+e); } } }
相关文章
- 重新封装了一下NODE-MONGO 使其成为一个独立的服务.可以直接通过get/post来操作
- 常见危险端口服务及对应的漏洞
- DotnetBrowser入门教程-(2)启动简单的Web服务
- 微服务架构案例(06):通过业务、应用、技术、存储方面,聊聊架构
- 从云服务到行业云,看可信云如何搭建云计算的最全标准?
- CentOS 下安装 LEMP 服务(nginx、MariaDB/MySQL 和 php)
- 通过AGC认证服务在iOS平台实现匿名登录功能
- 集成实践 | 手把手教你通过Cocos接入华为推送服务
- 《IT运维之道》——第2章 机遇就是选择大于努力2.1 IT开发还是IT服务
- 通过 ANE(Adobe Native Extension) 启动Andriod服务 推送消息(四)
- 呼叫中心应通过服务前置理念提升消费者的服务体验
- 日本7-11将通过呼叫中心提供免费翻译服务
- 本地通过虚拟机ip:端口访问不了虚拟机内的服务
- 使用Docker部署RabbitMQ 服务的方法
- 微服务通过feign.RequestInterceptor传递参数
- 通过Serverless认证服务在iOS平台实现手机号注册
- windows server 如要远程登录,你需要具有通过远程桌面服务进行登录的权限。
- 通过sd文件发布的FeatureAccess服务不能查看到图层
- WCF IIS上部署服务
- 无服务架构如何发展而来 怎样实现工作
- 从设计链到供应链 贸泽小批量分销提供高附加价值服务