Mig*_*ngi 5 asp.net-core-mvc asp.net-core
在.NET Core中使用Intranet应用程序工作,我想检索连接到AD用户的信息。当前,所有身份验证都由Windows处理,并且效果很好。有没有办法可以从AD中提取数据?我想获取诸如名字和姓氏,电子邮件,ID等信息。
使用.net core 2.1.1
从NuGet安装“ System.DirectoryServices”
using System.DirectoryServices;
var name = User.Identity.Name.Split('\\')[1]; *@I was getting name as domain\\name @*
DirectorySearcher ds = new DirectorySearcher();
ds.Filter = "(&(objectClass=user)(objectcategory=person)(name=" + name + "))";
SearchResult userProperty = ds.FindOne();
var userEmail = userProperty.Properties["mail"][0];
var userName = userProperty.Properties["displayname"][0];
Run Code Online (Sandbox Code Playgroud)
经过一周的尝试,我终于在使用 Novell.Directory.Ldap 包方面取得了进展。排除故障要容易得多,而且我不必担心运行双框架。
首先,转到包管理器控制台并输入:
Install-Package Novell.Directory.Ldap
Run Code Online (Sandbox Code Playgroud)
这会将包加载到您的项目并将其添加到 project.json 中。
那里有一些例子,但在查看了其中的大多数之后,它们并不是我真正需要的。我最终得到以下代码:
var logPath = System.IO.Path.GetTempFileName();
var logWriter = System.IO.File.CreateText(logPath);
var user = "cn="+User.Identity.Name.Split('\\')[1];
logWriter.WriteLine("Current Ldap results:");
LdapConnection ADconn = new LdapConnection();
ADconn.Connect("DC IP address", 389);
ADconn.Bind("DOMAIN\\username", "password");
logWriter.WriteLine(ADconn.GetSchemaDN());
LdapSearchResults lsc = ADconn.Search("ou=OrgUnit,dc=DOMAIN,dc=com",
LdapConnection.SCOPE_SUB,
user, attrs, false);
while (lsc.hasMore())
{
LdapEntry nextEntry = null;
try
{
nextEntry = lsc.next();
}
catch (LdapException e)
{
logWriter.WriteLine("Error: " + e.LdapErrorMessage);
//Exception is thrown, go for next entry
continue;
}
DisplayName = nextEntry.getAttribute("displayName").StringValue;
UserADId = new Guid((byte[])(Array)nextEntry.getAttribute("objectGuid").ByteValue).ToString();
EMail = nextEntry.getAttribute("mail").StringValue;
logWriter.WriteLine(DisplayName);
logWriter.WriteLine(UserADId);
logWriter.WriteLine(EMail);
}
logWriter.Dispose();
//Procced
//While all the entries are parsed, disconnect
ADconn.Disconnect();
Run Code Online (Sandbox Code Playgroud)
使用 Windows 身份验证,这允许从 AD 中提取用户的属性。一旦拉出,您就可以将它们分配给变量并使用它们!它还会在 C:\Windows\Temp\ 文件夹中创建一个 TMP 文件,该文件充当部署中的调试器。
希望这对其他人有帮助!
归档时间: |
|
查看次数: |
4585 次 |
最近记录: |