简体   繁体   English

Azure Function 函数如何使用托管标识获取对 Azure 表存储的引用?

[英]How can an Azure Function function get a reference to Azure Table storage using Managed Identity?

I have an Azure Function that has been assigned a System Identity:我有一个已分配系统标识的 Azure 函数:

系统分配的身份

I would like the Azure Function to access a Storage account.我希望 Azure 函数访问存储帐户。 The Function has the Reader & Data Access role on that storage account:该函数在该存储帐户上具有Reader & Data Access角色:

RBAC 权限

The Function has been configured with the name of the Storage account to use.函数已配置为要使用的存储帐户的名称。 The Function then tries to get an instance of CloudTableClient:然后,该函数尝试获取 CloudTableClient 的实例:

public async Task InitAsync(string accountsStorageName)
{
    var azureServiceTokenProvider = new AzureServiceTokenProvider();
    string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(accountsStorageName);
    
    var storageCredential = new StorageCredentials(accessToken);
    var storageAccount = new CloudStorageAccount(storageCredential, accountsStorageName, "core.windows.net", true);
                
     //  Gets the client to the account's Table storage.
    m_tableClient = storageAccount.CreateCloudTableClient();
}

Question

The above code fails because it is unable to get an access token:上面的代码失败,因为它无法获取访问令牌:

错误

How can an Azure Function get a reference to Azure Table storage using Managed Identity? Azure 函数如何使用托管标识获取对 Azure 表存储的引用?

Azure key vault can generate shared access signature tokens. Azure Key Vault 可以生成共享访问签名令牌。 A shared access signature provides delegated access to resources in your storage account.共享访问签名提供对存储帐户中资源的委派访问。 You can grant clients access to resources in your storage account without sharing your account keys.您可以授予客户端访问您的存储帐户中的资源的权限,而无需共享您的帐户密钥。 For more details, please refer to here欲知更多详情,请参阅此处

  1. Set an account shared access signature definition设置账户共享访问签名定义
$storageAccountName = ""
$keyVaultName = ""
$storageContext = New-AzStorageContext -StorageAccountName $storageAccountName -Protocol Https -StorageAccountKey Key1
$start = [System.DateTime]::Now.AddDays(-1)
$end = [System.DateTime]::Now.AddMonths(1)

$sasToken = New-AzStorageAccountSasToken -Service blob,file,Table,Queue -ResourceType Service,Container,Object -Permission "racwdlup" -Protocol HttpsOnly -StartTime $start -ExpiryTime $end -Context $storageContext


Set-AzKeyVaultManagedStorageSasDefinition -AccountName $storageAccountName -VaultName $keyVaultName -Name "<YourSASDefinitionName>" -TemplateUri $sasToken -SasType 'account' -ValidityPeriod ([System.Timespan]::FromDays(30))

在此处输入图片说明

  1. Configure access policy for Azure Function为 Azure Function 配置访问策略
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ObjectId "Azure Function MSI object id" -PermissionsToSecrets get,list
  1. code代码
  public static class Http
    {
        [FunctionName("Http")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            var azureServiceTokenProvider = new AzureServiceTokenProvider();
            var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

            SecretBundle sasToken =await kv.GetSecretAsync(secretIdentifier: "https://testkey02.vault.azure.net:443/secrets/teststorage08-sasToken");
            var storageCredential = new StorageCredentials(sasToken.Value);
            var accountsStorageName = "teststorage08";
            var storageAccount = new CloudStorageAccount(storageCredential, accountsStorageName, "core.windows.net", true);

            var tableClient = storageAccount.CreateCloudTableClient();
            var table =tableClient.GetTableReference("Customer");
            await table.CreateIfNotExistsAsync();
            CustomerEntity customer = new CustomerEntity("Harp", "Walter")
            {
                Email = "Walter@contoso.com",
                PhoneNumber = "425-555-0101"
            };

            TableOperation insertOrMergeOperation = TableOperation.InsertOrMerge(customer);
            TableResult result = await table.ExecuteAsync(insertOrMergeOperation);
            CustomerEntity insertedCustomer = result.Result as CustomerEntity;

            return new OkObjectResult(insertedCustomer);

        }       
    }

    public class CustomerEntity : TableEntity
    {
        public CustomerEntity()
        {
        }

        public CustomerEntity(string lastName, string firstName)
        {
            PartitionKey = lastName;
            RowKey = firstName;
        }

        public string Email { get; set; }

        public string PhoneNumber { get; set; }
    }

在此处输入图片说明

暂无
暂无

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

相关问题 在Azure函数中使用Azure Fluent SDK时,如何使用托管服务标识创建azure对象? - When using the Azure Fluent SDK in an Azure Function how can I create an azure object using a Managed Service Identity? 如何使用托管标识连接 Azure SQL DW - how to connect Azure SQL DW using Managed Identity using azure function Azure 函数 - 从 DefaultCredentials \ Managed Identity 获取令牌 - Azure Function - Get Token from DefaultCredentials \ Managed Identity Azure功能到表存储 - Azure Function into Table Storage 带有应用配置和托管标识的 Azure 函数 - 如何在本地调试 - Azure Function with App Config and managed identity - how to debug locally 如何将 Azure 托管标识与 Azure.Storage.Blobs.BlobServiceClient 一起使用? - How to use Azure managed identity with Azure.Storage.Blobs.BlobServiceClient? Azure 托管标识 - Function 应用程序和存储帐户 - DefaultAzureCredential 失败但 ManagedIdentityCredential 成功 - Azure Managed Identity - Function App & Storage Account - DefaultAzureCredential fails but ManagedIdentityCredential succeeds 如何使用 Azure 身份验证在 Azure Function 中获取当前用户身份? - How to get current user identity in Azure Function with Azure Authentication? Azure 存储帐户使用托管标识和 C# 进行身份验证 - Azure Storage Account authenticate using Managed Identity and C# 如何将 MSI(托管服务标识)与 Azure 存储模拟器一起使用? - How to use MSI(Managed Service Identity) with Azure storage emulator?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM