gpt4 book ai didi

c# - 如何在不模拟的情况下检查具有 [UserName] 和 [Password] 的用户是否是 [DomainName] 的域管理员?

转载 作者:太空狗 更新时间:2023-10-30 01:08:21 24 4
gpt4 key购买 nike

Impersonation example

我可以使用下一行代码检查用户域管理员:

using (Impersonation im = new Impersonation(UserName, Domain, Password))
{
System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
bool isDomainAdmin = identity.IsDomainAdmin(Domain, UserName, Password);
if (!isDomainAdmin)
{
//deny access, for example
}
}

IsDomainAdmin - 是扩展方法

public static bool IsDomainAdmin(this WindowsIdentity identity, string domain, string userName, string password)
{
Domain d = Domain.GetDomain(new DirectoryContext(DirectoryContextType.Domain, domain, userName, password));

using (DirectoryEntry de = d.GetDirectoryEntry())
{
byte[] domainSIdArray = (byte[])de.Properties["objectSid"].Value;
SecurityIdentifier domainSId = new SecurityIdentifier(domainSIdArray, 0);
SecurityIdentifier domainAdminsSId = new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, domainSId);
WindowsPrincipal wp = new WindowsPrincipal(identity);
return wp.IsInRole(domainAdminsSId);
}
}

但是,当调用方法 IsDomainAdmin 时,它会尝试将一些文件写入模拟用户的 %LOCALAPPDATA%,如果程序不是以管理员身份运行,它会抛出异常

Could not load file or assembly 'System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542)

最佳答案

您当然不需要用户的密码来验证用户是否是组的成员。那么,为什么不使用 DirectoryEntryDirectorySearcher 直接查询 AD?如果您还需要验证提供的密码是否正确,您可以使用 PrincipalContext.ValidateCredentials 在附加步骤中执行此操作。 (参见 PrincipalContext.ValidateCredentials Method (String, String))。

static void Main(string[] args) {
string userDomain = "somedomain";
string userName = "username";
string password = "apassword";

if (IsDomainAdmin(userDomain, userName)) {
string fullUserName = userDomain + @"\" + userName;
PrincipalContext context = new PrincipalContext(
ContextType.Domain, userDomain);
if (context.ValidateCredentials(fullUserName, password)) {
Console.WriteLine("Success!");
}
}
}

public static bool IsDomainAdmin(string domain, string userName) {
string adminDn = GetAdminDn(domain);
SearchResult result = (new DirectorySearcher(
new DirectoryEntry("LDAP://" + domain),
"(&(objectCategory=user)(samAccountName=" + userName + "))",
new[] { "memberOf" })).FindOne();
return result.Properties["memberOf"].Contains(adminDn);
}

public static string GetAdminDn(string domain) {
return (string)(new DirectorySearcher(
new DirectoryEntry("LDAP://" + domain),
"(&(objectCategory=group)(cn=Domain Admins))")
.FindOne().Properties["distinguishedname"][0]);
}

关于c# - 如何在不模拟的情况下检查具有 [UserName] 和 [Password] 的用户是否是 [DomainName] 的域管理员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9683373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com