繁体   English   中英

Azure - 以编程方式创建存储帐户

[英]Azure - Programmatically Create Storage Account

我已尝试使用以下代码在 Azure 中创建新的存储帐户:

获取令牌(成功 - 我收到了一个令牌):

var cc = new ClientCredential("clientId", "clientSecret");
var context = new AuthenticationContext("https://login.windows.net/subscription");
var result = context.AcquireTokenAsync("https://management.azure.com/", cc);

创建云存储凭据:

var credential = new TokenCloudCredentials("subscription", token);

创建云存储帐户(失败):

using (var storageClient = new StorageManagementClient(credentials))
{
    await storageClient.StorageAccounts.CreateAsync(new StorageAccountCreateParameters
    {
        Label = "samplestorageaccount",
        Location = LocationNames.NorthEurope,
        Name = "myteststorage",
        AccountType = "RA-GRS"
    });
}

错误:

ForbiddenError: 服务器未能验证请求。 验证证书是否有效并与此订阅相关联。

我不确定这是否是这些误导性消息之一,还是我在 Azure 中配置错误?

据我所知,Azure 现在提供两种类型的存储管理库。

Microsoft.Azure.Management.Storage
Microsoft.WindowsAzure.Management.Storage

Microsoft.Azure.Management.Storage 用于创建新的 ARM 存储。

Microsoft.WindowsAzure.Management.Storage 用于创建经典的 ARM 存储。

我猜您想创建新的 arm 存储,但您使用了“Microsoft.WindowsAzure.Management.Storage”库。 由于“Microsoft.WindowsAzure.Management.Storage”使用证书对请求进行身份验证,您将收到错误消息。 如果您想了解如何使用“Microsoft.WindowsAzure.Management.Storage”创建经典存储,建议您参考这篇文章

我假设您要创建新的 ARM 存储,建议您安装“Microsoft.Azure.Management.Storage”Nuget 包。

更详细的可以参考下面的代码。

    static void Main(string[] args)
    {
        var subscriptionId = "your subscriptionId";
        var clientId = "your client id";
        var tenantId = "your tenantid";
        var secretKey = "secretKey";
        StorageManagementClient StorageManagement = new StorageManagementClient(new Microsoft.Azure.TokenCloudCredentials(subscriptionId, GetAccessToken(tenantId, clientId, secretKey)));
       
        var re= StorageManagement.StorageAccounts.CreateAsync("groupname", "sotrage name",new Microsoft.Azure.Management.Storage.Models.StorageAccountCreateParameters() {
              Location = LocationNames.NorthEurope,
             AccountType = Microsoft.Azure.Management.Storage.Models.AccountType.PremiumLRS
        },new CancellationToken() { }).Result;

        Console.ReadKey();
    }

    static string GetAccessToken(string tenantId, string clientId, string secretKey)
    {
        var authenticationContext = new AuthenticationContext($"https://login.windows.net/{tenantId}");
        var credential = new ClientCredential(clientId, secretKey);
        var result = authenticationContext.AcquireTokenAsync("https://management.core.windows.net/",
            credential);

        if (result == null)
        {
            throw new InvalidOperationException("Failed to obtain the JWT token");
        }

        var token = result.Result.AccessToken;
        return token;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM