找不到该段“我”的资源

时间:2017-04-28 02:11:52

标签: azure azure-ad-graph-api

我正在使用Graph API来检索当前从Azure AD登录的用户的个人资料信息,遗憾的是我收到以下错误消息: {“odata.error”:{“code”:“Request_ResourceNotFound”,“message”:{“lang”:“en”,“value”:“找不到段'我'的资源。”}} }

以下是我的代码:

Uri serviceRoot = new Uri(serviceRootURL);
ActiveDirectoryClient adClient = new ActiveDirectoryClient(
                serviceRoot,
                async () => await GetAppTokenAsync());

var user = (User)await adClient.Me
            .Expand(x => x.Manager)
            .ExecuteAsync();

以下是我的GetAppTokenAsync()代码:

private static async Task<string> GetAppTokenAsync()
        {
            // Instantiate an AuthenticationContext for my directory (see authString above).
            AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);

            // Create a ClientCredential that will be used for authentication.
            // This is where the Client ID and Key/Secret from the Azure Management Portal is used.
            ClientCredential clientCred = new ClientCredential(clientID, clientSecret);

            // Acquire an access token from Azure AD to access the Azure AD Graph (the resource)
            // using the Client ID and Key/Secret as credentials.
            AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(resAzureGraphAPI, clientCred);

            // Return the access token.            
            return authenticationResult.AccessToken;
        }

2 个答案:

答案 0 :(得分:1)

从您的代码&#34;等待GetAppTokenAsync()&#34; ,您将获得一个仅限应用程序的令牌,它使用应用程序标识,而不是用户的身份。 &#34;(用户)等待adClient.Me&#34;如果该令牌与用户无关,则无法工作。

要使用app令牌获取用户管理员信息,您需要指定要查询的用户,以下代码供您参考:

            try
            {
                User manager = (User)await adClient.Users.GetByObjectId("5eba8883-c258-45d0-8add-a286a1ec1e91").Manager.ExecuteAsync();
            }
            catch (Exception ex)
            {

                throw;
            }

<强>更新

您可以将authorization code flow用于委派权限(用户身份)。如果您需要客户端库代码示例,可以参考this code sample。用户登录后,您可以使用以下代码获取当前登录用户的管理员:

            ActiveDirectoryClient client = AuthenticationHelper.GetActiveDirectoryClient();
            User manager = (User)await client.Me.Manager.ExecuteAsync();

答案 1 :(得分:0)

我使用具有 legacy Azure Active Directory api和'Application.ReadWrite.OwnedBy'权限的应用程序标识来解决Resource not found for the segment 'me'错误。 Microsoft Graph api中存在相同的权限,但是行为并不相同。 More information here