You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

触发UAC获权限实现C#向AD域添加用户遇权限问题求助

域用户创建DLL的UAC权限问题

我开发了一个用于向Active Directory域添加普通用户的DLL,核心创建用户的代码如下:

// User Information 
string username = "MyNewUser";
string fullname = "NewUser";
string description = "Cool Description for My New User";
string password = GeneratePassword();

// Fetch current Domain
string domainName = Environment.UserDomainName;
MessageBox.Show(Environment.UserName);
MessageBox.Show(System.Security.Principal.WindowsIdentity.GetCurrent().Name);

// New User PrincipalObject
UserPrincipal user = new UserPrincipal(new PrincipalContext(ContextType.Domain));

// Set Username & Password
user.SamAccountName = username + "@" + domainName;
user.Description = description;
user.DisplayName = fullname;
user.SetPassword(password);

// Activate User Account
user.Enabled = true;

// Save
user.Save();

由于仅Domain Admins具备添加域用户的权限,我尝试触发UAC以模拟域管理员身份执行代码,对应的权限判断逻辑如下:

WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool isAdmin = principal.IsInRole(WindowsBuiltInRole.AccountOperator);

if (!isAdmin)
{
    // If User is no admin, require elevated rights
    WindowsIdentity identity = WindowsIdentity.GetCurrent();
    WindowsPrincipal newPrincipal = new WindowsPrincipal(identity);

    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
    AppDomain.CurrentDomain.SetThreadPrincipal(newPrincipal);

    // Executing Code, that requires elevated rights
    createUser();

    // Restore Unauthenticated Principal Rights
    AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal);
}
else
{
    // If User is already Admin, just execute the Code
    createUser();
}

但触发UAC并登录域管理员账户后,代码却以NT-AUTHORITY\SYSTEM身份运行,导致new UserPrincipal()报错“Access Denied”。

期望效果:执行时弹出UAC提示,要求用户登录域管理员账户后执行代码。

已尝试的操作:

  • 修改DLL的app.manifest,添加<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />;
  • 在Visual Studio安装项目的LaunchConditions中添加“AdminUser”;
  • 右键选择“以管理员身份运行”安装文件。

现寻求解决该权限问题的帮助。

内容的提问来源于stack exchange,提问作者LukasVie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 04:52:49