0

我在使用 ASP.Net MVC 4 应用程序(框架 4.5)将用户从 csv 文件保存到活动目录时遇到问题。问题是第一个用户被正确保存,但第二个用户返回这个错误:

“/ADManagementStudio”应用程序中的服务器错误。

访问被拒绝。(来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))

说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.UnauthorizedAccessException:访问被拒绝。(来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))

ASP.NET 无权访问请求的资源。[...]

[...]

源错误:

在执行当前 Web 请求期间生成了未处理的异常。可以使用下面的异常堆栈跟踪来识别有关异常起源和位置的信息。

堆栈跟踪:

[UnauthorizedAccessException:访问被拒绝。(来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))]

[TargetInvocationException:调用目标引发了异常。]
System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args) +630438
ADManagementStudio.Web.Controllers.UsersController.AddUsers(HttpPostedFileBase 文件) +1437
ADManagementStudio。 Web.Controllers.UsersController.CSV(HttpPostedFileBase 文件) +23 lambda_method(Closure, ControllerBase, Object[]) +127 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary 2 参数) +39 System.Web.Mvc。 Async.<>c_ DisplayClass39.b _33() +120 System.Web.Mvc.Async.<>c_ DisplayClass4f.b _49() +452 System.Web.Mvc.Async.<>c_ DisplayClass37.b2 parameters) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary

_36(IAsyncResult asyncResult) +15
System.Web.Mvc.Async.<>c_ DisplayClass2a.b _20() +31 System.Web.Mvc.Async.<>c_ DisplayClass25.b _22(IAsyncResult asyncResult) +230
System.Web .Mvc.<>c_ DisplayClass1d.b _18(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c_ DisplayClass4.b _3(IAsyncResult ar) +15 System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
System.Web.Mvc.Async.<>c_ DisplayClass4.b _3(IAsyncResult ar) +15
System.Web.Mvc.<>c_ DisplayClass8.b _3(IAsyncResult asyncResult) +42
System.Web.Mvc.Async。 <> c_DisplayClass4.b_3(IAsyncResult ar) +15
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

我在 web.config 中使用模拟,但我认为只有第一个用户被保存而其他用户没有被保存,这很有趣,与其他用户有什么不同?(或者也许我只是因为我的糟糕经验而忽略了它)

这里是函数的代码:

private string AddUsers(HttpPostedFileBase file)
    {
        string tempFileName = string.Format("{0}_{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
        string filePath = Path.Combine(Server.MapPath("~/AD_App_Data/temp"), tempFileName);

        file.SaveAs(filePath);

        FileInfo tempFileInfo = new FileInfo(filePath);
        List<string[]> tempFileData = new List<string[]>();
        List<string> lines = new List<string>();

        using (StreamReader reader = new StreamReader(tempFileInfo.FullName, true))
        {
            string line = string.Empty;

            while ((line = reader.ReadLine()) != null)
            {
                string[] splitter = line.Split(';');

                lines.Add(line);
                tempFileData.Add(splitter);
            }
        }

        tempFileInfo.Delete();

        if ((tempFileData[0][0].ToLower() != "samaccountname") ||
            (tempFileData[0][1].ToLower() != "displayname"))
        {
            return "Error! sAMAccountName or displayName fields not found!";
        }

        try
        {
            string LDAPContextPath = string.Format(
                "LDAP://{0}/{1}",
                ActiveDirectoryManage.GetServerName(),
                ActiveDirectoryManage.GetLDAPUserPath());
            List<string> newUsersPassword = new List<string>();
            using (DirectoryEntry context = new DirectoryEntry(LDAPContextPath, "Administrator", "abcd,1234"))
            {
                foreach (string[] data in tempFileData.Skip(1))
                {
                    using (DirectoryEntry userEntry = context.Children.Add(string.Format("CN={0}", data[1]), "user"))
                    {
                        userEntry.Properties["sAMAccountName"].Value = data[0];
                        userEntry.CommitChanges();

                        for (int i = 1; i < data.Length; i++)
                        {
                            int number;

                            if (int.TryParse(data[i], out number))
                            {
                                userEntry.Properties[tempFileData[0][i]].Value = number;
                            }
                            else
                            {
                                userEntry.Properties[tempFileData[0][i]].Value = data[i];
                            }

                            userEntry.CommitChanges();
                        }

                        string newPassword = Membership.GeneratePassword(12, 0);

                        userEntry.Invoke("SetPassword", newPassword);
                        userEntry.CommitChanges();
                        newUsersPassword.Add(newPassword);
                        userEntry.Properties["userAccountControl"].Value = 512;
                        userEntry.CommitChanges();
                    }
                }

                Thread.Sleep(1000);
            }

            string timestamp = string.Format(
                "{0}{1}{2}-{3}{4}{5}",
                DateTime.Today.Hour, DateTime.Today.Minute, DateTime.Today.Second,
                DateTime.Today.Day, DateTime.Today.Month, DateTime.Today.Year);
            string doneFileName = string.Format("{0}_{1}.csv", file.FileName, timestamp);
            string donePath = Path.Combine(Server.MapPath("~/AD_App_Data/done"), doneFileName);

            using (StreamWriter writer = new StreamWriter(donePath))
            {
                writer.WriteLine(AppendPassword(lines[0], "password"));

                for (int i = 1; i < lines.Count; i++)
                {
                    writer.WriteLine(AppendPassword(lines[i], newUsersPassword[i - 1]));
                }
            }

            return doneFileName;
        }
        catch (DirectoryServicesCOMException ex)
        {
            return "Error! Exception! " + ex.Message;
        }
    }

谢谢你的建议

4

2 回答 2

0

如果您使用模拟,您需要确保被模拟的用户有足够的权限来修改/创建活动目录中的对象。如果模拟用户不是域管理员或没有设置自定义权限,则几乎不会出现这种情况。

我建议你放弃模拟,或者将应用程序池作为在活动目录中具有有限权限的域帐户运行(在这里考虑最低权限,只给它完成工作所需的权限),或者在代码中创建一个模拟上下文手动使用与建议的应用程序池帐户具有相同限制的域帐户。

SO 答案中有几个链接可以帮助您在代码中冒充另一个用户。

于 2013-06-10T09:45:59.207 回答
0

好的,伙计们,我终于成功了!出于某种我暂时忽略的原因,我以编程方式模拟具有足够权限的用户来在每次迭代中管理 AD。

这里是页面上的链接,描述了如何以编程方式实现服务器端模拟。

下面是我如何使用它:

private string AddUsers(HttpPostedFileBase file)
    {
        string tempFileName = string.Format("{0}_{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
        string filePath = Path.Combine(Server.MapPath("~/AD_App_Data/temp"), tempFileName);

        file.SaveAs(filePath);

        FileInfo tempFileInfo = new FileInfo(filePath);
        List<string[]> tempFileData = new List<string[]>();
        List<string> lines = new List<string>();

        using (StreamReader reader = new StreamReader(tempFileInfo.FullName, true))
        {
            string line = string.Empty;

            while ((line = reader.ReadLine()) != null)
            {
                string[] splitter = line.Split(';');

                lines.Add(line);
                tempFileData.Add(splitter);
            }
        }

        tempFileInfo.Delete();

        if ((tempFileData[0][0].ToLower() != "samaccountname") ||
            (tempFileData[0][1].ToLower() != "displayname"))
        {
            return "Error! sAMAccountName or displayName fields not found!";
        }

        List<string> users = new List<string>();

        try
        {
            string LDAPContextPath = string.Format(
                "LDAP://{0}/{1}",
                ActiveDirectoryManage.GetServerName(),
                ActiveDirectoryManage.GetLDAPUserPath());
            List<string> newUsersPassword = new List<string>();

            foreach (string[] data in tempFileData.Skip(1))
            {
                if (impersonateValidUser("Administrator", ActiveDirectoryManage.GetDomainName(), "abcd,1234"))
                {
                    using (DirectoryEntry context = new DirectoryEntry(LDAPContextPath, "Administrator", "abcd,1234"))
                    {
                        users.Add(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                        using (DirectoryEntry userEntry = context.Children.Add(string.Format("CN={0}", data[1]), "user"))
                        {
                            userEntry.Properties["sAMAccountName"].Value = data[0];
                            userEntry.CommitChanges();

                            for (int i = 1; i < data.Length; i++)
                            {
                                int number;

                                if (int.TryParse(data[i], out number))
                                {
                                    userEntry.Properties[tempFileData[0][i]].Value = number;
                                }
                                else
                                {
                                    userEntry.Properties[tempFileData[0][i]].Value = data[i];
                                }

                                userEntry.CommitChanges();
                            }

                            string newPassword = Membership.GeneratePassword(12, 0);

                            userEntry.Invoke("SetPassword", newPassword);
                            userEntry.CommitChanges();
                            newUsersPassword.Add(newPassword);
                            userEntry.Properties["userAccountControl"].Value = 512;
                            userEntry.CommitChanges();
                        }
                    }
                    undoImpersonation();
                }
                else
                {
                    return "Error! Impersonation Failed";
                }
            }


            string timestamp = string.Format(
                "{0}{1}{2}-{3}{4}{5}",
                DateTime.Today.Hour, DateTime.Today.Minute, DateTime.Today.Second,
                DateTime.Today.Day, DateTime.Today.Month, DateTime.Today.Year);
            string doneFileName = string.Format("{0}_{1}.csv", file.FileName, timestamp);
            string donePath = Path.Combine(Server.MapPath("~/AD_App_Data/done"), doneFileName);

            using (StreamWriter writer = new StreamWriter(donePath))
            {
                writer.WriteLine(AppendPassword(lines[0], "password"));

                for (int i = 1; i < lines.Count; i++)
                {
                    writer.WriteLine(AppendPassword(lines[i], newUsersPassword[i - 1]));
                }
            }

            return doneFileName;
        }
        catch (Exception ex)
        {
            string error = "Error! Exception! " + ex.Message + "\n\n";

            foreach (string s in users)
            {
                error = error + s + "\n\n";
            }

            return error;
        }
    }

我希望这篇文章能有所帮助!

于 2013-06-10T18:57:22.793 回答