如何使用交互式登录从 Azure AD 获取我自己的用户属性(电子邮件、UPN 等)?

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

新来的男孩,所以请友善。 ;)

我正在尝试编写一个 C# 控制台应用程序,以通过使用交互式登录从 Azure AD 获取我自己的用户属性(例如 BusinessPhones、displayName、givenName、id、jobTitle、mail、mobilePhone、officeLocation、preferredLanguage、surname 和 userPrincipalName) ?使用 AAD 身份验证时弹出的标准登录窗口。

我开始这样做,但“Microsoft.IdentityModel.Clients.ActiveDirectory”已被弃用。有人可以帮忙吗?

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Graph;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string clientId = "my client ID from app reg";
        string authority = "https://login.microsoftonline.com/your-tenant-id";
        string resource = "https://graph.microsoft.com";
c# .net azure azure-active-directory
1个回答
0
投票

创建 Azure AD 应用程序并授予 User.Read API 权限:

enter image description here

使用以下端点生成授权码并使用用户帐户登录:

https://login.microsoftonline.com/TenantID/oauth2/v2.0/authorize?
&client_id=ClientID
&response_type=code
&redirect_uri=https://replyUrlNotSet
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345

enter image description here

您可以使用以下代码来获取用户详细信息:

using Microsoft.Graph;
using Azure.Identity;

class Program
{
    static async Task Main(string[] args)
    {
        
        var scopes = new[] { "User.Read" };
        var tenantId = "TenantID";
        var clientId = "ClientID";
        var clientSecret = "ClientSecret";
        var authorizationCode = "authcodefromabove";

        var options = new AuthorizationCodeCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
        };

        var authCodeCredential = new AuthorizationCodeCredential(
            tenantId, clientId, clientSecret, authorizationCode, options);

        var graphClient = new GraphServiceClient(authCodeCredential, scopes);

        try
        {
            // Fetch user details using GET request to Microsoft Graph API
            var result = await graphClient.Me.GetAsync();

            // Output user details
            Console.WriteLine($"User ID: {result.Id}");
            Console.WriteLine($"Display Name: {result.DisplayName}");
            Console.WriteLine($"Email: {result.Mail}");
            Console.WriteLine($"Job Title: {result.JobTitle}");
            // Add more properties as needed

        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error fetching user details: {ex.Message}");
        }
    }
}

enter image description here

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