Azure AD - 将所有用户基本信息拉入列表

时间:2017-08-29 21:50:31

标签: c# asp.net azure azure-web-sites azure-active-directory

我是Azure的新手,我正在使用ASP.NET MVC 4模板项目 我的目标是将所有用户从Azure AD拉到一个可枚举的列表中,然后我可以在以后搜索。

目前,我收到了以下错误:

Server Error in '/' Application
Object reference not set to an instance of an object
...
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

或者这个,取决于我注释掉的.Where(...)条款:

The token for accessing the Graph API has expired. Click here to sign-in and get a new access token.

点击该链接会调用以下网址:

https://login.microsoftonline.com/<MY TENANT GUID>/oauth2/authorize?client_id=<MY APP ID>&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%<Bunch of alphanumeric gibberish>&nonce=<More alphanumeric gibberish>-client-SKU=ID_NET&x-client-ver=1.0.40306.1554

点击该链接会尝试某些操作,但只是将我放回同一页面并返回相同的错误,并且不会执行任何其他操作。

UserProfileController.cs

private ApplicationDbContext db = new ApplicationDbContext();
private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private string graphResourceID = "https://graph.windows.net";

public async Task<Collection<IUser>> GetAllUsers()
{
    var userList = new Collection<IUser>();
    try
    {
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        Uri servicePointUri = new Uri(graphResourceID);
        Uri serviceRoot = new Uri(servicePointUri, tenantID);
        ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
            async () => await GetTokenForApplication());

        // use the token for querying the graph to get the user details

        var result = await activeDirectoryClient.Users
            //.Where(u => u.JobTitle.Equals("Cool Dudes"))    // Works fine when uncommented, otherwise gives me a server error
            .ExecuteAsync();

        while (result.MorePagesAvailable)
        {
            userList = userList.Concat(result.CurrentPage.ToList()) as Collection<IUser>;
            await result.GetNextPageAsync();
        }
    }
    catch (Exception e)
    {
        if (Request.QueryString["reauth"] == "True")
        {
            // Send an OpenID Connect sign-on request to get a new set of tokens.
            // If the user still has a valid session with Azure AD, they will not
            //  be prompted for their credentials.
            // The OpenID Connect middleware will return to this controller after
            //  the sign-in response has been handled.
            HttpContext.GetOwinContext()
                .Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }

        return userList;
    }

    return userList;
}

public async Task<ActionResult> Admin()
{
    try
    {
        var user = await GetAllUsers();

        return View(user
            //.Where(u => u.JobTitle.Equals("Cool Dudes"))  // When this is uncommented and the one in GetAllUsers is commented out, I get an error saying "The token for accessing the Graph API has expired. Click here to sign-in and get a new access token."
            );
    }
    catch (AdalException)
    {
        // Return to error page.
        return View("Error");
    }
    // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
    catch (Exception)
    {
        return View("Relogin");
    }
}

public void RefreshSession()
{
    HttpContext.GetOwinContext().Authentication.Challenge(
        new AuthenticationProperties { RedirectUri = "/UserProfile" },
        OpenIdConnectAuthenticationDefaults.AuthenticationType);
}

public async Task<string> GetTokenForApplication()
{
    string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
    string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
    string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;

    // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
    ClientCredential clientcred = new ClientCredential(clientId, appKey);
    // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
    AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
    AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
    return authenticationResult.AccessToken;
}

Admin.cshtml

@using Microsoft.Azure.ActiveDirectory.GraphClient
@model IEnumerable<IUser>

@{
    ViewBag.Title = "Admin";
}
<h2>@ViewBag.Title.</h2>

<table class="table table-bordered table-striped">
    @foreach (var user in Model)
    {
        <tr>
            <td>Display Name</td>
            <td>@user.DisplayName</td>
            <td>Job Title</td>
            <td>@user.JobTitle</td>
        </tr>
    }
</table>

我在这里缺少什么?我的while循环逻辑错了吗?我是否可能使用现在过时的方式来阅读这些信息?这是权限问题吗?

修改

缩小范围:

  • GetAllUsers(以及可选Admin)具有Where子句时,Admin会返回空白页面,但不会出现错误
  • Admin具有Where子句时,会返回图表错误
  • 如果没有Where子句,则返回服务器错误

所以我认为GetAllUsers没有正确返回数据。

2 个答案:

答案 0 :(得分:1)

基于this blog post by Jonathan Huss,我能够将我的代码中的这部分代码从项目默认Azure AD Graph API转换为较新的Microsoft Graph API

在我的Models文件夹中(可能放在Utility文件夹或其他东西中)我添加以下代码:

<强> AzureAuthenticationProvider.cs

using System.Configuration;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;

namespace <PROJECT_NAME>.Models
{
    class AzureAuthenticationProvider : IAuthenticationProvider
    {
        private string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
        private string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
        private string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];

        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
            string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
            ClientCredential creds = new ClientCredential(clientId, appKey);
            // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
            AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
            AuthenticationResult authResult = await authenticationContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);

            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
        }
    }
}

回到 UserProfileController.cs ,我们有:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Web;
using System.Web.Mvc;
using System.Threading.Tasks;
using Microsoft.Azure.ActiveDirectory.GraphClient;  // Will eventually be removed
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OpenIdConnect;
using <PROJECT_NAME>.Models;
using Microsoft.Graph;
using User = Microsoft.Graph.User;  // This is only here while I work on removing references to Microsoft.Azure.ActiveDirectory.GraphClient

namespace <PROJECT_NAME>.Controllers
{
    [Authorize]
    public class UserProfileController : Controller
    {
        public async Task<List<User>> GetAllUsers()
        {
            List<User> userResult = new List<User>();

            GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
            IGraphServiceUsersCollectionPage users = await graphClient.Users.Request().Top(500).GetAsync(); // The hard coded Top(500) is what allows me to pull all the users, the blog post did this on a param passed in
            userResult.AddRange(users);

            while (users.NextPageRequest != null)
            {
                users = await users.NextPageRequest.GetAsync();
                userResult.AddRange(users);
            }

            return userResult;
        }

        // Return all users from Azure AD as a proof of concept
        public async Task<ActionResult> Admin()
        {
            try
            {
                var user = await GetAllUsers();

                return View(user
                    );
            }
            catch (AdalException)
            {
                // Return to error page.
                return View("Error");
            }
            // if the above failed, the user needs to explicitly re-authenticate for the app to obtain the required token
            catch (Exception)
            {
                return View("Relogin");
            }
        }
    }
}

我原始帖子中的RefreshSessionGetTokenForApplication方法仍然存在,但在我修改代码时可能会被AzureAuthenticationProvider类替换

最后, Admin.cshtml 的一个小变化,我改变了

@using Microsoft.Azure.ActiveDirectory.GraphClient
@model IEnumerable<IUser>

@using Microsoft.Graph
@model List<User>

答案 1 :(得分:0)

根据错误消息,它不应该与where原因相关。该问题导致令牌过期。

在这种情况下,您可以使用客户端凭据流获取应用程序令牌而不是委托令牌,因为没有使用当前用户的上下文。对于此流程,您可以使用方法AcquireTokenAsync(string resource, ClientCredential clientCredential)

请告诉我们是否有帮助。