使用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
相关产品推荐
相关产品推荐

