或許當前域下的用戶列表api
[Authorize] public async Task<ActionResult> Index() { var userList = new List<IUser>(); try { var client = AuthenticationHelper.GetActiveDirectoryClient(); var pagedCollection = await client.Users.ExecuteAsync(); while (pagedCollection != null) { userList.AddRange(pagedCollection.CurrentPage.ToList()); pagedCollection = await pagedCollection.GetNextPageAsync(); } } catch (Exception e) { if (e.Message == "Authorization Required.") { HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); return View(userList); } } return View(userList); }
Index被修飾爲[Authorize],當用戶沒有登陸就會跳轉到登陸界面要求用戶登陸,當身份被驗證後將執行Action的代碼。async
var client = AuthenticationHelper.GetActiveDirectoryClient();
上面這行代碼得到了Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClient對象,該對象是對Azure AD Graph API的封裝,該實例提供經過租戶對象 ID和經過使用「Me」別名的兩種Azure AD Graph REST API進行的服務。ui
Microsoft.Azure.ActiveDirectory.GraphClient.ActiveDirectoryClien實例暴露的屬性,能夠經過對Context和Query來了解到對Url的封裝。spa
好比3d
l Applications中的BaseUri的值是https://graph.chinacloudapi.cn/<你的租戶ID>code
l Users的Query的Url是https://graph.chinacloudapi.cn/<你的租戶ID>/users對象
l DeletedDirectoryObjectsde Query的Url是https://graph.chinacloudapi.cn/<你的租戶ID>/deletedDirectoryObjectsblog
有意思的是Me,Me是別名僅當使用 OAuth 受權代碼授予類型(3 重)身份驗證時,此別名纔可用。此別名不區分大小寫。它將替換 URL 中的對象 ID 或租戶域。使用此別名時,Graph API 將從附加到請求的令牌中提供的聲明獲取用戶。因此Me屬性中提供的CreatedObjects、CreatedOnBehalfOf、DirectReports、Manager、MemberOf、Members、OwnedObjects、Owners這些操做的Url都是以下格式ip
https://graph.chinacloudapi.cn/<你的租戶ID>/me/<操做名稱>ci
因此說ActiveDirectoryClient提供的很是良好的RESTAPI的封裝。
var pagedCollection = await client.Users.ExecuteAsync();
Users以IPagedCollection<IUser>對象返回,每Page包含必定數量的User,咱們須要遍歷集合中的User對象。
最後將咱們得到的User集合返回給View。對應的View的代碼以下
@model IEnumerable<Microsoft.Azure.ActiveDirectory.GraphClient.IUser> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <div class="table-responsive"> <table id="directoryObjects" class="table table-bordered table-striped table-condensed"> <tr> <th> 用戶名 </th> <th> 顯示名稱 </th> <th> 別名 </th> <th> 職務 </th> <th /> </tr> @foreach (var item in Model) { var user = item as Microsoft.Azure.ActiveDirectory.GraphClient.User; <tr> <td> @Html.ActionLink(item.UserPrincipalName, "Details", new { objectId = item.ObjectId }) </td> <td> @Html.DisplayFor(modelItem => user.DisplayName) </td> <td> @Html.DisplayFor(modelItem => user.MailNickname) </td> <td> @Html.DisplayFor(modelItem => user.JobTitle) </td> <td> @Html.ActionLink("Edit", "Edit", new { objectId = item.ObjectId }) <br /> @Html.ActionLink("Delete", "Delete", new { objectId = item.ObjectId }) <br /> </td> </tr> } </table> </div>
運行結果如圖