我正在使用 Windows 身份验证并访问用户名。
IIdentity winId = HttpContext.Current.User.Identity;
string name = winId.Name;
但我想获取其他详细信息,例如用户全名和电子邮件 ID。
由于您位于 Windows 网络上,因此您需要查询 Active Directory 来搜索用户,然后获取其属性,例如电子邮件
这是一个示例函数DisplayUser
给出了IIdentity
在经过 Windows 身份验证的网络上,查找用户的email
:
public static void Main() {
DisplayUser(WindowsIdentity.GetCurrent());
Console.ReadKey();
}
public static void DisplayUser(IIdentity id) {
WindowsIdentity winId = id as WindowsIdentity;
if (id == null) {
Console.WriteLine("Identity is not a windows identity");
return;
}
string userInQuestion = winId.Name.Split('\\')[1];
string myDomain = winId.Name.Split('\\')[0]; // this is the domain that the user is in
// the account that this program runs in should be authenticated in there
DirectoryEntry entry = new DirectoryEntry("LDAP://" + myDomain);
DirectorySearcher adSearcher = new DirectorySearcher(entry);
adSearcher.SearchScope = SearchScope.Subtree;
adSearcher.Filter = "(&(objectClass=user)(samaccountname=" + userInQuestion + "))";
SearchResult userObject = adSearcher.FindOne();
if (userObject != null) {
string[] props = new string[] { "title", "mail" };
foreach (string prop in props) {
Console.WriteLine("{0} : {1}", prop, userObject.Properties[prop][0]);
}
}
}
gives this:
编辑:如果您收到“错误的用户/密码错误”运行代码的帐户必须有权访问用户域。如果您在 ASP.NET 中运行代码,则 Web 应用程序必须在具有域访问权限的凭据的应用程序池下运行。看here了解更多信息
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)