Как найти отображаемое имя пользователя Active Directory в веб-приложении на С#?
Я пишу веб-приложение, которое использует проверку подлинности Windows, и я могу с радостью получить имя пользователя, используя что-то вроде:
string login = User.Identity.Name.ToString();
Но мне не нужно их имя для входа. Я хочу их DisplayName. Я уже несколько часов стучала головой...
Могу ли я получить доступ к моей организации AD через веб-приложение?
Ответы
Ответ 1
Как насчет этого:
private static string GetFullName()
{
try
{
DirectoryEntry de = new DirectoryEntry("WinNT://" + Environment.UserDomainName + "/" + Environment.UserName);
return de.Properties["displayName"].Value.ToString();
}
catch { return null; }
}
Ответ 2
См. соответствующий вопрос: Active Directory: получение информации о пользователе
Смотрите также: Howto: (почти) все в Active Directory через С# и более конкретно раздел " Перечислить свойства объекта".
Если у вас есть путь к подключению к группе в домене, может оказаться полезным следующий фрагмент:
GetUserProperty("<myaccount>", "DisplayName");
public static string GetUserProperty(string accountName, string propertyName)
{
DirectoryEntry entry = new DirectoryEntry();
// "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
entry.Path = "LDAP://...";
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(SAMAccountName=" + accountName + ")";
search.PropertiesToLoad.Add(propertyName);
SearchResultCollection results = search.FindAll();
if (results != null && results.Count > 0)
{
return results[0].Properties[propertyName][0].ToString();
}
else
{
return "Unknown User";
}
}
Ответ 3
Используйте это:
string displayName = UserPrincipal.Current.DisplayName;
Ответ 4
В случае, если кто-то заботится, мне удалось взломать это:
/// This is some imaginary code to show you how to use it
Session["USER"] = User.Identity.Name.ToString();
Session["LOGIN"] = RemoveDomainPrefix(User.Identity.Name.ToString()); // not a real function :D
string ldappath = "LDAP://your_ldap_path";
// "LDAP://CN=<group name>, CN =<Users>, DC=<domain component>, DC=<domain component>,..."
Session["cn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "cn");
Session["displayName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "displayName");
Session["mail"] = GetAttribute(ldappath, (string)Session["LOGIN"], "mail");
Session["givenName"] = GetAttribute(ldappath, (string)Session["LOGIN"], "givenName");
Session["sn"] = GetAttribute(ldappath, (string)Session["LOGIN"], "sn");
/// working code
public static string GetAttribute(string ldappath, string sAMAccountName, string attribute)
{
string OUT = string.Empty;
try
{
DirectoryEntry de = new DirectoryEntry(ldappath);
DirectorySearcher ds = new DirectorySearcher(de);
ds.Filter = "(&(objectClass=user)(objectCategory=person)(sAMAccountName=" + sAMAccountName + "))";
SearchResultCollection results = ds.FindAll();
foreach (SearchResult result in results)
{
OUT = GetProperty(result, attribute);
}
}
catch (Exception t)
{
// System.Diagnostics.Debug.WriteLine(t.Message);
}
return (OUT != null) ? OUT : string.Empty;
}
public static string GetProperty(SearchResult searchResult, string PropertyName)
{
if (searchResult.Properties.Contains(PropertyName))
{
return searchResult.Properties[PropertyName][0].ToString();
}
else
{
return string.Empty;
}
}
Ответ 5
Существует проект CodePlex для Linq to AD, если вам интересно.
Он также рассмотрен в книге LINQ Unleashed for С# от Paul Kimmel - он использует вышеупомянутый проект в качестве отправной точки.
не связан ни с одним из источников - я просто недавно прочитал книгу