在本机应用程序中使用 ClientSecretCredential 向 BlobServiceClient 进行身份验证

Authenticate to BlobServiceClient using ClientSecretCredential in a native app

我正在尝试对本机 .net 应用程序中的 azure blob 存储进行身份验证。以下代码产生 403。我没有看到任何身份验证流程被触发(例如,没有同意或 TFA 提示),但也许这不应该是预期的。客户端注册配置为具有 user_impersonation 范围的本机应用程序。我想知道我应该采取什么步骤来解决问题。

var credential = new ClientSecretCredential(tenantid, appid, clientSecret);                                
client = new BlobServiceClient(accountUri, credential);

// Make a service request to verify we've successfully authenticated
var foo= await client.GetPropertiesAsync();

回复:

Azure.RequestFailedException: This request is not authorized to perform this operation using this permission.
RequestId:73e54cff-401e-004d-7211-685a00000000
Time:2020-08-01T14:37:01.2280787Z
Status: 403 (This request is not authorized to perform this operation using this permission.)
ErrorCode: AuthorizationPermissionMismatch

Headers:
x-ms-request-id: 73e54cff-401e-004d-7211-685a00000000
x-ms-client-request-id: a9a34270-db76-424b-ac33-750b2cdb2ffb
x-ms-version: 2019-12-12
x-ms-error-code: AuthorizationPermissionMismatch
Date: Sat, 01 Aug 2020 14:37:00 GMT
Server: Windows-Azure-Blob/1.0,Microsoft-HTTPAPI/2.0
Content-Length: 279
Content-Type: application/xml

如果要客户端凭据流访问Azure存储,我们需要将Azure RABC角色(Storage Blob Data Contributor)分配给Azure AD应用程序。详情请参考document

例如

  1. Register Azure AD application via Azure Portal.

  2. Create a client secret for the application

  3. Azure AD 应用程序的 Azure RABC 角色(存储 Blob 数据贡献者)。

  4. 代码

var clientId = "42e0d***2d988c4";
            var secret = "Gbx2***fQpIjoae:";
            var tenant = "e4c9ab4***2a757fb";

            ClientSecretCredential credential = new ClientSecretCredential(tenant, clientId, secret);
            string accountName = "jimtestdiag924";

            string url = string.Format("https://{0}.blob.core.windows.net/", accountName);
            var client = new BlobServiceClient(new Uri(url), credential);

            var foo = await client.GetPropertiesAsync();