下面是一个使用AAD B2C按PrincipalName搜索用户的示例代码:
using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AADB2CUserSearch
{
class Program
{
// AAD B2C tenant details
private static string tenantId = "your-tenant-id";
private static string clientId = "your-client-id";
private static string clientSecret = "your-client-secret";
private static string policy = "your-sign-in-policy";
static async Task Main(string[] args)
{
// Initialize the GraphServiceClient
GraphServiceClient graphClient = await GetGraphServiceClient();
// Search for users by PrincipalName
string principalName = "user@example.com";
var users = await SearchUsersByPrincipalName(graphClient, principalName);
// Display the search results
Console.WriteLine($"Found {users.Count} user(s) with PrincipalName '{principalName}':");
foreach (var user in users)
{
Console.WriteLine($"- {user.DisplayName} ({user.Id})");
}
}
static async Task GetGraphServiceClient()
{
// Create a confidential client application
IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}/v2.0")
.Build();
// Acquire an access token
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult authResult = await confidentialClientApp.AcquireTokenForClient(scopes).ExecuteAsync();
// Initialize the GraphServiceClient
GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
{
requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
return Task.CompletedTask;
}));
return graphClient;
}
static async Task> SearchUsersByPrincipalName(GraphServiceClient graphClient, string principalName)
{
var queryOptions = new List
{
new QueryOption("$filter", $"signInNames/any(x: x/value eq '{principalName}' and x/type eq 'emailAddress')")
};
var request = graphClient.Users.Request(queryOptions);
var response = await request.GetAsync();
return response.CurrentPage.ToList();
}
}
}
注意替换以下变量值:
tenantId
:AAD B2C租户的IDclientId
:应用程序的客户端IDclientSecret
:应用程序的客户端密钥policy
:登录策略的名称此示例使用Microsoft Graph .NET SDK和Microsoft Identity Client库来与AAD B2C进行交互。首先,我们将创建一个机密客户端应用程序,并使用其凭据获取访问令牌。然后,我们使用GraphServiceClient进行搜索并获取用户信息。
在Main
方法中,我们首先初始化GraphServiceClient,然后调用SearchUsersByPrincipalName
方法来搜索具有指定PrincipalName的用户。最后,我们遍历搜索结果并在控制台上显示每个用户的显示名称和ID。