コードでの SAS 定義の作成と Shared Access Signature トークンの取得 (レガシ)

キー コンテナー内に格納されている Shared Access Signature (SAS) トークンを使用して、ご利用のストレージ アカウントを管理できます。 詳細については、SAS を使用した Azure Storage リソースへの制限付きアクセスの許可に関するページを参照してください。

注意

共有キーによる承認のセキュリティと使いやすさを強化できるように、Azure ロールベースのアクセス制御 (Azure RBAC) を使用してストレージ アカウントをセキュリティで保護することをお勧めします。

この記事では、SAS 定義を作成し、SAS トークンをフェッチする .NET コードのサンプルを示します。 Key Vault マネージド ストレージ アカウント用に生成されたクライアントなど、詳細については、ShareLink のサンプルを参照してください。 SAS トークンを作成して保存する方法の詳細については、「Key Vault と Azure CLI を使用してストレージ アカウント キーを管理する」または「Key Vault と Azure PowerShell を使用してストレージ アカウント キーを管理する」を参照してください。

コード サンプル

次の例では、SAS テンプレートを作成します。

private static string BuildSasDefinitionTemplate(bool readOnly) =>
    new StringBuilder("sv=2018-03-28")  // service version
        .Append("&spr=https")           // HTTPS only
        .Append("&ss=bf")               // blobs and files only
        .Append("&srt=o")               // applies to objects only
        .Append(readOnly ? "&sp=r" : "&sp=rw")  // read-only or read-write
        .ToString();

このテンプレートを使用して、SAS 定義を作成できます。

string sasDefinitionName = BuildSasDefinitionName(Tag, readOnly, duration);
SasDefinitionAttributes sasDefinitionAttributes = new SasDefinitionAttributes
{
    Enabled = true,
};

Dictionary<string, string> tags = new Dictionary<string, string>
{
    [Tag] = "1",
};

SasDefinitionBundle createdSasDefinition = await storageClient.SetSasDefinitionAsync(
    storageAccountName,
    sasDefinitionName,
    sasTemplate,
    SasTokenType.Account,
    duration,
    sasDefinitionAttributes,
    tags,
    s_cancellationTokenSource.Token);

SAS 定義を作成したら、SecretClient を使用してシークレットなどの SAS トークンを取得できます。 次のように、ストレージ アカウント名、ダッシュ、シークレット名の順に記述する必要があります。

// Build our SAS template, get an existing SAS definition, or create a new one.
string sasTemplate = BuildSasDefinitionTemplate(readOnly);
string sasDefinitionName = await GetOrCreateSasDefinitionAsync(storageClient, storageAccountName, sasTemplate, days, readOnly);

// Now we can create a SecretClient and generate a new SAS token from the storage account and SAS definition names.
SecretClient secretClient = new SecretClient(vaultUri, credential, options);
KeyVaultSecret sasToken = await secretClient.GetSecretAsync($"{storageAccountName}-{sasDefinitionName}", cancellationToken: s_cancellationTokenSource.Token);

Shared Access Signature トークンの有効期限が間もなく切れる場合は、同じシークレットを再度フェッチして、新しいものを生成することができます。

取得した Key Vault SAS トークンを使用して Azure Storage サービスにアクセスする方法のガイドについては、アカウント SAS を使用した Blob service へのアクセスに関する記事をご覧ください

注意

アプリでは、ストレージから 403 を取得した場合、SAS の更新に向けた準備が行われる必要があります。これにより、キーが侵害され、通常のローテーション期間よりも速くローテンションを行う必要があるケースを処理することができます。

次のステップ