System.UnauthorizedAccessException调用UserPrincipal.SetPassword

Ric*_*ard 2 c# active-directory

当我运行此代码时

PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
                                                                adHost,
                                                                adRoot,
                                                                ContextOptions.SimpleBind,
                                                                adUsername,
                                                                adPassword);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
user.SetPassword(password);
user.Save();
Run Code Online (Sandbox Code Playgroud)

我得到了这个例外

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.UnauthorizedAccessException: One or more input parameters are invalid
Run Code Online (Sandbox Code Playgroud)

代码使用"runas/user:命令行运行:( domainadminuser也是本地管理员)使用相同的凭据创建上下文(domainadminuser)我已检查所有用户名,密码等是否正确填充它是否适用于我正在创建PrincipalContext的方式吗?

我完全卡住了.有没有人有任何想法?

谢谢

[更新] 这是我用来使它工作的代码.我想也许ValidateCredentials可以将其付诸实践(可能)

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, parameters["adHost"] );
ctx.ValidateCredentials(parameters["adUsername"], parameters["adPassword"], ContextOptions.SimpleBind);
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
user.SetPassword(password);
user.Save();
Run Code Online (Sandbox Code Playgroud)

小智 5

以下是我们在内部开发的密码请求管理系统正常运行的代码,请尝试告诉我:

PrincipalContext context = new PrincipalContext( ContextType.Domain, null, adAdminLogin, adAdminPassword );
UserPrincipal user = UserPrincipal.FindByIdentity( context, adUserLogin );
user.SetPassword( adUserNewPassword );
Run Code Online (Sandbox Code Playgroud)