我不推荐使用存储帐户的连接字符串并使用 MSI 进行身份验证。我的服务使用 Microsoft.WindowsAzure.Storage 包来执行所有操作(主要是表相关)。我知道这是一个遗留包,将其升级到新支持的 SDK(例如 Azure.Data.Tables)将使 MSI 的使用变得容易,但我们现在不想升级 SDK,因为它涉及大量代码更改。
我尝试使用下面的代码:
var credential = new DefaultAzureCredential();
var accessToken = credential.GetToken(new TokenRequestContext(scopes: new string[] { "https://storage.azure.com/.default" }));
var tokenCredential = new Microsoft.WindowsAzure.Storage.Auth.TokenCredential(initialToken: accessToken.Token);
StorageCredentials storageCredentials = new StorageCredentials(tokenCredential);
var tableClient = new CloudTableClient(new Uri(tableEndpoint), storageCredentials);
_table = tableClient.GetTableReference(tableName);
_table.CreateIfNotExists(tableRequestOptions);
但它报告错误“此服务不支持令牌凭证”。 这很奇怪,因为我可以使用 tokenCredential 来构造 StorageCredentials,但我无法使用它。 任何建议将不胜感激。谢谢!
有没有办法通过 Microsoft.WindowsAzure.Storage 包将 MSI 用于存储帐户?
您可以使用下面的代码从
Microsoft.WindowsAzure.Storage
包中创建 Azure 表存储。
您需要两个包(
Microsoft.WindowsAzure.Storage
和 Microsoft.Azure.Services.AppAuthentication
)来执行下面的代码。以下是软件包参考和安装命令:
安装:
dotnet add package Microsoft.Azure.Services.AppAuthentication --version 1.6.2
dotnet add package WindowsAzure.Storage --version 9.3.3
注意: 两个软件包均已弃用。供您参考。
包装参考:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.6.2" />
<PackageReference Include="WindowsAzure.Storage" Version="9.3.3" />
</ItemGroup>
</Project>
代码:
using System;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.Azure.Services.AppAuthentication;
class Program
{
static async Task Main(string[] args)
{
string accountName = "venkat123";
string tableName = "sampletab";
await createTable(accountName, tableName);
Console.WriteLine("Table created successfully!");
}
public static async Task createTable(string accountName, string tableName)
{
string tableEndpoint = string.Format("https://{0}.table.core.windows.net/", accountName);
var token = await new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/");
var tokenCredential = new TokenCredential(token);
var storageCredentials = new StorageCredentials(tokenCredential);
var tableClient = new CloudTableClient(new Uri(tableEndpoint), storageCredentials);
var table = tableClient.GetTableReference(tableName);
table.CreateIfNotExistsAsync().Wait();
}
}
上面的代码使用托管身份和
Microsoft.WindowsAzure.Storage.Table.CloudTableClient
在 Azure 表存储中创建一个表。
输出:
Table created successfully!
传送门: