使用 ASP.NET MVC (.NET) 的 Active Directory






4.25/5 (8投票s)
使用 ASP.NET MVC 的 Active Directory
引言
在 C# 中访问 Microsoft 的 Active Directory 时,很多人感到困惑,不知道如何开始。本文旨在向您展示如何以简单的方式使用 C# 与 Active Directory 通信。我创建了一个简单的 Web 应用程序,使用 ASP.NET MVC 与 Active Directory 交互。此应用程序仅在 Active Directory 上执行三个操作:
- 获取所有用户
- 获取所有组
- 重置用户密码
背景
您应该具备一些 ASP.NET MVC 的基本知识。
Active Directory
- 安装 Windows Server 2012 R2。
- 安装 Active Directory 域服务。
- 在新的林中创建新的域。我将其命名为“
MBS.Com
”。 - 添加组织单元并将其命名为“
DevOU
”。 - 在 OU 中添加一些用户和组。
Using the Code
有两种命名空间可以与 C# 的 Active Directory 通信:
System.DirectoryServices.ActiveDirectory
System.DirectoryServices.AccountManagement
(这是我使用的)
注意
在我的例子中,IIS 服务器和目录域控制器位于同一台机器上,才能成功运行任务。
- 在您的控制器中添加一个名为
HomePage
的 Action,其中包含两个按钮,一个用于用户,另一个用于组。public ActionResult HomePage() { return View(); }
- 为这个 Action 添加 View
@{ ViewBag.Title = "HomePage"; } @*<h2>HomePage</h2>*@ <br /> <br /> <div class="row text-center"> <div class="col lg-6"> @Html.ActionLink ("Users", "GetAllUsers", "Home", null, new { @class = "btn btn-primary" }) @Html.ActionLink ("Groups", "GetAllGroups", "Home", null, new { @class = "btn btn-primary" }) </div> </div>
- 在 Models 文件夹中添加两个用于用户和组的类
public class User { public int Id { get; set; } [Display(Name = "Display Name")] public string DisplayName { get; set; } public string Samaccountname { get; set; } } public class Group { public int Id { get; set; } [Display(Name = "Group Name")] public string GroupName { get; set; } }
- 然后我们将实现三个将在 Active Directory 上执行的方法:获取所有用户、获取所有组、设置密码
public ActionResult GetAllUsers() { List<User> ADUsers = GetallAdUsers(); return View(ADUsers); } public ActionResult GetAllGroups() { List<Group> ADGroups = GetallGroups(); return View(ADGroups); } //if you want to get Groups of Specific OU you have to add OU Name in Context public static List<User> GetallAdUsers() { List<User> AdUsers = new List<User>(); //MBS.com My Domain Controller which i created //OU=DevOU --Organizational Unit which i created //and create users and groups inside it var ctx = new PrincipalContext(ContextType.Domain, "MBS","OU=DevOU,DC=MBS,DC=com"); UserPrincipal userPrin = new UserPrincipal(ctx); userPrin.Name = "*"; var searcher = new System.DirectoryServices.AccountManagement.PrincipalSearcher(); searcher.QueryFilter = userPrin; var results = searcher.FindAll(); foreach (Principal p in results) { AdUsers.Add(new User { DisplayName = p.DisplayName, Samaccountname = p.SamAccountName }); } return AdUsers; } public ActionResult ResetPassword(string Samaccountname) { //i get the user by its SamaccountName to change his password PrincipalContext context = new PrincipalContext (ContextType.Domain, "MBS", "OU=DevOU,DC=MBS,DC=com"); UserPrincipal user = UserPrincipal.FindByIdentity (context, IdentityType.SamAccountName, Samaccountname); //Enable Account if it is disabled user.Enabled = true; //Reset User Password string newPassword = "P@ssw0rd"; user.SetPassword(newPassword); //Force user to change password at next logon dh optional user.ExpirePasswordNow(); user.Save(); TempData["msg"] = "<script>alert('Password Changed Successfully');</script>"; return RedirectToAction("GetAllUsers"); } //if you want to get all Groups of Specific OU you have to add OU Name in Context public static List<Group> GetallGroups() { List<Group> AdGroups = new List<Group>(); var ctx = new PrincipalContext(ContextType.Domain, "MBS", "OU=DevOU,DC=MBS,DC=com"); GroupPrincipal _groupPrincipal = new GroupPrincipal(ctx); PrincipalSearcher srch = new PrincipalSearcher(_groupPrincipal); foreach (var found in srch.FindAll()) { AdGroups.Add(new Group { GroupName = found.ToString() }); } return AdGroups; }
- 然后为
GetAllUsers
action 添加 view。@model IEnumerable<ActiveDirectory.Models.User> @{ ViewBag.Title = "GetAllUsers"; } <br /> <form> <div class="form-group"> <label for="SearchInput" class="col-sm-2 col-form-label">Search for User</label> <div class="col-md-10"> <input type="text" class="form-control" id="SearchInput" onkeyup="myFunction()" placeholder="Enter User"> </div> </div> </form> <br /> <br /> @Html.Raw(TempData["msg"]) <table class="table table-bordered table-striped" id="tblUsers"> <tr> <th> @Html.DisplayNameFor(model => model.DisplayName) </th> <th> @Html.DisplayNameFor(model => model.Samaccountname) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.DisplayName) </td> <td> @Html.DisplayFor(modelItem => item.Samaccountname) </td> <td> @Html.ActionLink("Reset Password", "ResetPassword", new { Samaccountname = item.Samaccountname }) </td> </tr> } </table> @section scripts { <script> function myFunction() { var input, filter, table, tr, td, i; input = document.getElementById("SearchInput"); filter = input.value.toUpperCase(); table = document.getElementById("tblUsers"); tr = table.getElementsByTagName("tr"); for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[0]; if (td) { if (td.innerHTML.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } } </script> }
- 为
GetAllGroups
Action 添加另一个 view。@model IEnumerable<ActiveDirectory.Models.Group> @{ ViewBag.Title = "GetAllGroups"; } <br /> <table class="table table-striped table-bordered"> <tr> <th> @Html.DisplayNameFor(model => model.GroupName) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.GroupName) </td> </tr> } </table>
注释
所有这些功能都在我创建的特定组织单元“DevOU
”上工作。
要获取 Active Directory 的所有用户和组,只需从上下文中删除“OU
”即可。
历史
- 2019年3月7日:初始版本