如何使用 C# 和 Graph API 从 Azure 目录获取用户详细信息

问题描述 投票:0回答:1

我想使用 userPrincipleName 或对象 ID 获取用户详细信息。

我尝试这样做,但他们给了我下面提到的错误。

无法计算表达式。此错误的常见原因是尝试将 lambda 传递到委托中。

这是c#代码

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;

namespace UserProperties;

public class GraphHandler
{
    public GraphServiceClient GraphClient { get; set; }

    public GraphHandler(string tenantId, string clientId, string clientSecret)
    {
        GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
    }
    public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
    {
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud            
        };

        var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
        var scopes = new[] { "https://graph.microsoft.com/.default" };

        return new GraphServiceClient(clientSecretCredential, scopes);
    }

    public async Task<User?> GetUser(string userPrincipalName)
    {
        return await GraphClient.Users[userPrincipalName].GetAsync();
    }

    public void userDetail()
    {
        var user =  GraphClient.Me.GetAsync();
        Console.WriteLine(user);
    }
}

我怎样才能摆脱这个问题,有人可以建议我吗?

我想从 azure 目录获取用户详细信息。

谢谢你

c# .net-core azure-active-directory microsoft-graph-api azure-web-app-service
1个回答
1
投票

当您使用

ClientSecretCredential
并调用
/me
端点时发生错误。

  • ClientSecretCredential
    是非交互流,
    /me
    端点仅适用于用户交互流。
  • 因此,要么切换到用户交互流程,要么使用
    ClientSecretCredential
    并调用
    users/UserId
    端点。

授予应用程序API使用权限

ClientSecretCredential
:

enter image description here

并通过更改

GraphClient.Users[userId].GetAsync()
来修改代码,如下所示:

using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using System;
using System.Threading.Tasks;

namespace UserProperties
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var tenantId = "TenantID";
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
        }

        public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
        {
            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            return new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task userDetail()
        {
            try
            {
                // Example usage to get user details directly
                var userId = "UserID"; // Replace with the desired user's ID
                var user = await GraphClient.Users[userId].GetAsync();

                // Print user ID and DisplayName
                Console.WriteLine($"User ID: {user.Id}");
                Console.WriteLine($"Display Name: {user.DisplayName}");
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting user details: {ex.Message}");
            }
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            GraphHandler handler = new GraphHandler();

            // Example usage to get my details
            await handler.userDetail();
        }
    }
}

用户详细信息成功显示如下:

如果您想调用

/me
端点,则授予 User.Read 委托 API 权限并引用此 MsDoc (除非客户端凭据提供程序选择任何流程) 并选择交互式流程进行身份验证.

更新:

要获取用户个人资料照片,请使用以下代码:

using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;

namespace UserProperties
{
    public class GraphHandler
    {
        public GraphServiceClient GraphClient { get; set; }

        public GraphHandler()
        {
            var tenantId = "TenantID";
            var clientId = "ClientID";
            var clientSecret = "ClientSecret";
            GraphClient = CreateGraphClient(tenantId, clientId, clientSecret);
        }

        public GraphServiceClient CreateGraphClient(string tenantId, string clientId, string clientSecret)
        {
            var options = new TokenCredentialOptions
            {
                AuthorityHost = Azure.Identity.AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new Azure.Identity.ClientSecretCredential(tenantId, clientId, clientSecret, options);
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            return new GraphServiceClient(clientSecretCredential, scopes);
        }

        public async Task<User> GetUser(string userId)
        {
            try
            {
                var user = await GraphClient.Users[userId].GetAsync();
                return user;
            }
            catch (ServiceException ex)
            {
                Console.WriteLine($"Error getting user details: {ex.Message}");
                return null;
            }
        }

        public async Task PrintProfilePicture(string userId)
        {
            var user = await GetUser(userId);
            if (user != null)
            {
                try
                {
                    using (var photoStream = await GraphClient.Users[userId].Photo.Content.GetAsync())
                    {
                        var fileName = $"{userId}_profile_pic.jpg";
                        using (var fileStream = File.Create(fileName))
                        {
                            await photoStream.CopyToAsync(fileStream);
                            Console.WriteLine($"Profile picture saved as: {fileName}");
                        }
                    }
                }
                catch (ServiceException ex)
                {
                    Console.WriteLine($"Error downloading profile picture: {ex.Message}");
                }
            }
        }
    }

    class Program
    {
        static async Task Main(string[] args)
        {
            var handler = new GraphHandler();
            var userId = "UserID"; // Replace with the desired user's ID
            await handler.PrintProfilePicture(userId);
        }
    }
}

参考:

获取用户-Microsoft Graph v1.0 |微软

© www.soinside.com 2019 - 2024. All rights reserved.