首页 > 解决方案 > 如何使用 StorageManagementClient 的客户端密码在服务/守护程序应用程序中获取 MSAL 令牌?

问题描述

我使用什么范围值来获取 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.comhttps://graph.microsoft.com/.defaulthttps://graph.microsoft.com/.defaulthttps:// /storage.azure.com,用户阅读。使用多个范围会更早地抛出。

这个工作 - 例如,我可以创建存储帐户 - 如果我改为在 .NET Core 控制台应用程序中使用以下 ADAL 代码来获取令牌:

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 门户|活动目录|应用程序注册中,在身份验证下,启用了允许公共客户端流,在 API 权限下,应用程序具有默认值 | Azure Storage\user_impersonation(唯一可用的权限)。在这两种情况下,我都使用 Microsoft.Identity.Client 4.36.2。

标签: .netmsal

解决方案


对于标准客户端凭据流,请使用/.default. 例如, https://graph.microsoft.com/.default。Azure AD 将自动在客户端凭据流的访问令牌中包含管理员已同意的所有应用级权限。请求访问所有权限的范围。如果要获取所有静态范围应用程序的令牌,请附加.default 到 API 的应用程序 ID URI

ResourceId = "someAppIDURI";

var scopes = new [] {  ResourceId+"/.default"};

范围应该是:- 范围:[“https://management.core.windows.net/.default”]

您还可以提供足够的权限。

在此处输入图像描述

在这里阅读更多。


推荐阅读