【发布时间】:2021-12-05 15:04:12
【问题描述】:
我使用什么范围值来获取 C# 桌面框架 (4.8) 应用程序的身份验证令牌,该应用程序使用适用于 Azure 存储 API 的应用注册/客户端密钥?还是我需要做其他事情?在 MSAL 示例之后,我有这样的代码:
var authorityUri = new Uri($"https://login.microsoftonline.com/{TenantId}");
var app = Microsoft.Identity.Client.ConfidentialClientApplicationBuilder
.Create(ApplicationId)
.WithClientSecret(PrimaryClientSecretValue)
.WithAuthority(authorityUri)
.Build();
string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
AuthenticationResult result = null;
result = app.AcquireTokenForClient(scopes)
.ExecuteAsync()
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
var appSecretCredentials = new Microsoft.Rest.TokenCredentials(result.AccessToken, result.TokenType);
var storageManagementClient = new Microsoft.Azure.Management.Storage.StorageManagementClient(appSecretCredentials);
storageManagementClient.SubscriptionId = SubscriptionId;
var allStorageAccountsResponse = storageManagementClient.StorageAccounts
.ListWithHttpMessagesAsync()
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
var allStorageAccountsList = allStorageAccountsResponse.Body.ToArray();
Console.WriteLine("Storage account list");
foreach (var currStorageAccount in allStorageAccountsList)
Console.WriteLine(currStorageAccount.Name);
这总是失败并显示“身份验证失败”。我尝试了以下范围值,但没有任何改进:https://management.azure.com、https://graph.microsoft.com/.default、https://graph.microsoft.com/.default、https://storage.azure.com、User.Read。使用多个作用域会更早地抛出。
如果我改为在 .NET Core 控制台应用程序中使用以下 ADAL 代码来获取令牌,则此 WORKS - 例如,我可以创建存储帐户:
var clientCredential = new ClientCredential(clientId, clientSecret);
var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
var result = context.AcquireTokenAsync("https://management.azure.com/", clientCredential)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
var appSecretCredentials = new Microsoft.Rest.TokenCredentials(result.AccessToken);
var storageManagementClient = new Microsoft.Azure.Management.Storage.StorageManagementClient(appSecretCredentials);
storageManagementClient.SubscriptionId = subscriptionId;
// ...remainder as above...
在 Azure 门户|Active Directory|应用注册中,在身份验证下启用了允许公共客户端流,在 API 权限下,应用具有默认值 | Azure Storage\user_impersonation(唯一可用的权限)。在这两种情况下,我都使用 Microsoft.Identity.Client 4.36.2。
【问题讨论】: