Csharp/C#教程:在.NET MVC中使用LDAP /网络凭据validation用户分享


在.NET MVC中使用LDAP /网络凭据validation用户

我正在使用.NET中的MVC 3应用程序,我对LDAP没有太多经验,但我希望能够简单地validation用户是否存在。 我不需要validation用户名和密码组合,如下例所示:

ASP.Net MVC中的LDAP身份validation

虽然这几乎是我想要做的。 我只需要在添加用户名之前validation用户名。

有没有一种简单的方法在.NET / MVC中执行此操作

使用System.DirectoryServices.AccountManagement命名空间并通过更改IdentityType枚举来传递用户名或专有名称(例如CN = John Doe)。

 public bool UserExists(string username) { PrincipalContext domain = new PrincipalContext(ContextType.Domain); // locate the user UserPrincipal user = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username); return user != null; } 

您可以使用LdapConnection和SearchRequest来实现。

获取所有用户的示例:

上述就是C#学习教程:在.NET MVC中使用LDAP /网络凭据validation用户分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

 ///  /// Gets the LDAP users from the LDAP server. ///  /// The LDAP server, string format: "LDAP://172.22.100.10:389/OU=AT,O=ON" /// Type of the directory. /// The user. /// The password. /// The domain (AD only). /// String list of LDAP users. public List GetLdapUsers(string ldapServer, LocalDirectoryType directoryType, string user, string password, string domain) { List LdapUsers = new List(); string serverName = Regex.Match(ldapServer, @"^.+//(.+?):").Groups[1].ToString(); string distinguishedName = ldapServer.Substring(ldapServer.LastIndexOf("/") + 1); LdapConnection connection = new LdapConnection(new LdapDirectoryIdentifier(serverName)); switch (directoryType) { case LocalDirectoryType.ActiveDirectory: connection.AuthType = AuthType.Ntlm; break; case LocalDirectoryType.eDirectory: connection.AuthType = AuthType.Basic; break; } // attempt to connect try { connection.Bind(new NetworkCredential(user, password)); } catch (Exception exception) { Trace.WriteLine(exception.ToString()); } // run search for users SearchResponse response = connection.SendRequest(new SearchRequest(distinguishedName, "(|(objectClass=person)(objectClass=user))", System.DirectoryServices.Protocols.SearchScope.Subtree, null)) as SearchResponse; // extract users from results based on server type if (directoryType == LocalDirectoryType.ActiveDirectory) { foreach (SearchResultEntry entry in response.Entries) { if (entry.Attributes.Contains("sAMAccountName") && entry.Attributes["sAMAccountName"][0].ToString() != String.Empty) LdapUsers.Add(domain + "\" + entry.Attributes["sAMAccountName"][0].ToString()); } } else { foreach (SearchResultEntry entry in response.Entries) { if (entry.Attributes.Contains("cn") && entry.Attributes["cn"][0].ToString() != String.Empty) { LdapUsers.Add("cn=" + entry.Attributes["cn"][0].ToString()); } } } return LdapUsers; } 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/961090.html

(0)
上一篇 2021年11月25日
下一篇 2021年11月25日

精彩推荐