首页 > 解决方案 > 无法使用 Microsoft.Graph 检索显示名称、用户名和所有其他属性

问题描述

我有一个 Blazor 应用程序(可能是任何 Web 应用程序),它使用 Microsoft.Graph 从 AD B2C 检索用户数据。但是检索到的用户的所有属性都是空的。我已授予 User.Read.All 权限。这是我的代码:

        IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
            .Create(_adB2CSettings.ClientId)
            .WithTenantId(_adB2CSettings.TenantId)
            .WithClientSecret(_adB2CSettings.ClientSecret)
            .Build();

        ClientCredentialProvider authenticationProvider = new ClientCredentialProvider(confidentialClientApplication);

        GraphServiceClient graphServiceClient = new GraphServiceClient(authenticationProvider);

        return await graphServiceClient.Users[userId].Request().GetAsync();

我什至试过

return await graphServiceClient.Users[userId].Request().Select("displayName,mail,country,contacts,contactFolders").GetAsync();

但是id没有帮助。我错过了什么?

标签: azure-ad-b2cblazor-server-side

解决方案


如果要检索用户的属性,可以试试下面的代码,完美地将用户的属性输出到控制台:


using System;
using Microsoft.Identity.Client;
using Microsoft.Graph.Auth;
using Microsoft.Graph;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace call_api

{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)



        {
            IConfidentialClientApplication app;
            app = ConfidentialClientApplicationBuilder.Create("{client id}")
                    .WithClientSecret("{Client Secret}")
                    .WithAuthority(new Uri("https://login.microsoftonline.com/{B2C tenant id}"))
                    .Build();



            AuthenticationResult result = null;
            string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
            result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
            string accesstoken = result.AccessToken;

            /*Console.WriteLine(accesstoken);*/

            ClientCredentialProvider authProvider = new ClientCredentialProvider(app);

            GraphServiceClient graphClient = new GraphServiceClient(authProvider);


            var user = await graphClient.Users["{user id}"].Request().GetAsync();

            Console.WriteLine("user properties:" + JsonConvert.SerializeObject(user));

        }
    }
}
    

在此处输入图像描述


推荐阅读