通过编写代码提取共享访问签名令牌Fetch shared access signature tokens in code

可以使用密钥保管库中的共享访问签名令牌来管理存储帐户。You can manage your storage account with the shared access signature tokens in your key vault. 本文提供了提取 SAS 令牌并对其执行操作的 C# 代码示例。This article provides examples of C# code that fetches a SAS token and performs operations with it. 有关如何创建和存储 SAS 令牌的信息,请参阅使用密钥保管库和 Azure CLI 管理存储帐户密钥使用密钥保管库和 Azure PowerShell 管理存储帐户密钥For information on how to create and store SAS tokens, see Manage storage account keys with Key Vault and the Azure CLI or Manage storage account keys with Key Vault and Azure PowerShell.

代码示例Code samples

在此示例中,代码从密钥保管库中提取 SAS 令牌,使用它创建新的存储帐户,并创建新的 Blob 服务客户端。In this example, the code fetches a SAS token from your key vault, uses it to create a new storage account, and creates a new Blob service client.

// After you get a security token, create KeyVaultClient with vault credentials.
var kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(securityToken));

// Get a shared access signature token for your storage from Key Vault.
// The format for SecretUri is https://<YourKeyVaultName>.vault.azure.cn/secrets/<ExamplePassword>
var sasToken = await kv.GetSecretAsync("SecretUri");

// Create new storage credentials by using the shared access signature token.
var accountSasCredential = new StorageCredentials(sasToken.Value);

// Use the storage credentials and the Blob storage endpoint to create a new Blob service client.
var accountWithSas = new CloudStorageAccount(accountSasCredential, new Uri ("https://myaccount.blob.core.chinacloudapi.cn/"), null, null, null);

var blobClientWithSas = accountWithSas.CreateCloudBlobClient();

如果共享访问签名令牌即将过期,则可以从密钥保管库中提取共享访问签名令牌,并更新代码。If your shared access signature token is about to expire, you can fetch the shared access signature token from your key vault and update the code.

// If your shared access signature token is about to expire,
// get the shared access signature token again from Key Vault and update it.
sasToken = await kv.GetSecretAsync("SecretUri");
accountSasCredential.UpdateSASToken(sasToken);

后续步骤Next steps