我有代码直接在ADFS的活动目录中创建用户 我的示例代码 -
PrincipalContext principalContext = null;
try
{
principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal usr = UserPrincipal.FindByIdentity(principalContext, txt_username.Text);
if (usr != null)
{
MessageBox.Show(txt_username.Text + " already exists. Please use a different User Logon Name.");
}
else
{
UserPrincipal userPrincipal = new UserPrincipal(principalContext);
userPrincipal.Surname = txt_lastname.Text;
userPrincipal.GivenName = txt_firstname.Text;
userPrincipal.EmailAddress = txt_email.Text;
userPrincipal.UserPrincipalName = txt_username.Text + "@ad.net";
userPrincipal.SamAccountName = txt_username.Text;
userPrincipal.DisplayName = txt_lastname.Text + " " + txt_firstname.Text;
userPrincipal.SetPassword(txt_pwd.Text);
userPrincipal.Enabled = true;
userPrincipal.PasswordNeverExpires = true;
userPrincipal.Save();
MessageBox.Show("user Created Sucessfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed to create PrincipalContext. Exception: " + ex);
}
它与窗口应用程序的工作正常,但如果我在asp.net中放入相同的应用程序,则抛出错误 -
userPrincipal异常:访问被拒绝
任何建议
由于
答案 0 :(得分:1)
这意味着用于向Active Directory进行身份验证的帐户无权创建帐户。
除非另行指定,否则用于运行ASP.NET应用程序的帐户由IIS创建,除了运行它的服务器之外没有任何权限。您有两种选择:
PrincipalContext
,并使用有权创建帐户的凭据:principalContext = new PrincipalContext(ContextType.Domain, null, "DOMAIN\username", "password");
答案 1 :(得分:0)
在此行principalContext = new PrincipalContext(ContextType.Domain);
中构建PrincipalContext时,请确保传递其他参数,例如AD服务器名称,用户名,密码等。它应该解决任何权限问题。使用的用户名和密码应具有在AD中创建用户的权限。例如:principalContext = new PrincipalContext(ContextType.Domain, ADSERVER, $"OU=New Users,DC=MYDOMAIN,DC=CO,DC=UK", USERNAME, PASSWORD);