You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Microsoft Graph查询当前应用注册及服务主体ID

基于客户端凭据流的应用登录与ID获取

现有登录代码(证书认证)

var certificateBytes = Convert.FromBase64String(certificate);
X509Certificate2 adCertificate = new X509Certificate2(certificateBytes, certificatePassword);
IConfidentialClientApplication confidentialClientApp = ConfidentialClientApplicationBuilder.Create(_clientId)
    .WithAuthority(AzureCloudInstance.AzurePublic, _tenantId)
    .WithCertificate(adCertificate)
    .Build();
var storageProperties = new StorageCreationPropertiesBuilder("TokenCache.plaintext", tokenCacheDirectory)
    .WithUnprotectedFile()
    .Build();
var cacheHelper = MsalCacheHelper.CreateAsync(storageProperties).Result;
cacheHelper.RegisterCache(_confidentialClientApp.UserTokenCache);

var silentToken = await _confidentialClientApp.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();
var graphServiceClient = new Microsoft.Graph.GraphServiceClient(new Microsoft.Graph.DelegateAuthenticationProvider(async (requestMessage) =>
{
    var authResult = await _confidentialClientApp.AcquireTokenForClient(new string[] { "https://graph.microsoft.com/.default" }).ExecuteAsync();
    requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
})
);

获取应用注册对象ID与服务主体ID

完成登录后,可通过Microsoft Graph API实现你需要的两个功能,具体代码如下:

1. 获取应用注册对象ID

public async Task<Guid> GetMyAppRegistrationId()
{
    var appRegistration = await graphServiceClient.Applications
        .Request()
        .Filter($"appId eq '{_clientId}'")
        .Select("id")
        .FirstOrDefaultAsync();

    if (appRegistration == null)
        throw new InvalidOperationException("未找到与当前客户端ID匹配的应用注册");
    
    return Guid.Parse(appRegistration.Id);
}

2. 获取服务主体ID

public async Task<Guid> GetServicePrincipalIdOfAppRegistration()
{
    var servicePrincipal = await graphServiceClient.ServicePrincipals
        .Request()
        .Filter($"appId eq '{_clientId}'")
        .Select("id")
        .FirstOrDefaultAsync();

    if (servicePrincipal == null)
        throw new InvalidOperationException("未找到与当前客户端ID匹配的服务主体");
    
    return Guid.Parse(servicePrincipal.Id);
}

注意事项

  • 需确保你的应用注册已配置Application.Read.All应用权限,并获得管理员同意,否则Graph API查询会返回权限不足的错误。

内容的提问来源于stack exchange,提问作者johnstaveley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 13:22:40