programing

최신 Azure SDK를 사용하여 Blob 상에서 공유 액세스시그니처를 취득하는 방법NET API v12?

javajsp 2023. 4. 24. 22:26

최신 Azure SDK를 사용하여 Blob 상에서 공유 액세스시그니처를 취득하는 방법NET API v12?

이전에는 다음과 같이 v11 Azure SDK API를 사용하여 Blob에 공유 액세스 서명을 만들 수 있었습니다.

var containerName = "mycontainer";
var blobName = "myblob";

CloudStorageAccount storageAccount 
 = CloudStorageAccount.Parse(<StorageConnectionString>);

CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

CloudBlobContainer container = blobClient.GetContainerReference(containerName);


SharedAccessBlobPermissions permission = SharedAccessBlobPermissions.Read;

TimeSpan clockSkew = TimeSpan.FromMinutes(15d);
TimeSpan accessDuration = TimeSpan.FromMinutes(15d);

var blobSAS = new SharedAccessBlobPolicy
{
    SharedAccessStartTime = DateTime.UtcNow.Subtract(clockSkew),
    SharedAccessExpiryTime = DateTime.UtcNow.Add(accessDuration) + clockSkew,
    Permissions = permissions
};

CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

string sasBlobToken = blob.GetSharedAccessSignature(blobSAS);

...

.v12를 사용하고 싶다. API를 대체하는 CloudBlobClient타타에 BlobServiceClient,CloudBlobContainer타타에 BlobContainerClient ★★★★★★★★★★★★★★★★★」CloudBlockBlob타타에 BlobClient

, 「」, 「」는GetSharedAccessSignature에서 할 수 있습니다.CloudBlockBlob에서 인스턴스를 사용할 수 없습니다.BlobClient★★★★★★ 。

질문.

에서 BlobClientSDK .instance를 를 만듭니다.NET API v12?

Sajeetharan의 답변으로 BlobSasBuilder 클래스가 실제로 존재하는지 알아보게 되었습니다.

서버상에 작성하는 방법은 다음과 같습니다.

//  Creates a client to the BlobService using the connection string.
var blobServiceClient = new BlobServiceClient(storageConnectionString);

//  Gets a reference to the container.
var blobContainerClient = blobServiceClient.GetBlobContainerClient(<ContainerName>);

//  Gets a reference to the blob in the container
BlobClient blobClient = containerClient.GetBlobClient(<BlobName>);

//  Defines the resource being accessed and for how long the access is allowed.
var blobSasBuilder = new BlobSasBuilder
{
    StartsOn = DateTime.UtcNow.Subtract(clockSkew), 
    ExpiresOn = DateTime.UtcNow.Add(accessDuration) + clockSkew,
    BlobContainerName = <ContainerName>,
    BlobName = <BlobName>,
};
    
//  Defines the type of permission.
blobSasBuilder.SetPermissions(BlobSasPermissions.Write);
       
//  Builds an instance of StorageSharedKeyCredential      
var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);

//  Builds the Sas URI.
BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential);

클라이언트측에서 사용하는 방법은 다음과 같습니다.

//  Builds the URI to the blob storage.
UriBuilder fullUri = new UriBuilder()
{
    Scheme = "https",
    Host = string.Format("{0}.blob.core.windows.net", <AccountName>),
    Path = string.Format("{0}/{1}", <ContainerName>, <BlobName>),
    Query = sasQueryParameters.ToString()
};

//  Get an instance of BlobClient using the URI.
var blobClient = new BlobClient(fullUri.Uri, null);

//  Upload stuff in the blob.
await blobClient.UploadAsync(stream);

부록

@one2012가 코멘트에서 언급한 바와 같이, Azure에서 볼 수 있는 모든 기능을 보여주는 페이지는 이 답변 후 몇 달 후에 게시되었습니다.스토리지 네임스페이스이 링크는 자세한 정보를 얻는데 도움이 됩니다.

갱신하다

서버측에서는 Azure 기능을 사용하고 있습니다.Azure 스토리지와 기능의 Managed Identity를 접속하고 있습니다.스토리지를 연결할 때 더 이상 계정을 사용하지 않고 스토리지의 끝점만 사용합니다.

BlobContainerClient blobContainerClient = new(new Uri(containerEndpoint), new DefaultAzureCredential());  

서버 좀 더 . 제가 코드이기 때문입니다. 왜냐하면 저는 이전에CloudStorageAccount.Credentials.GetExportKeys()어카운트 키를 취득하는 방법.Managed Identity(관리 아이덴티티)

//  Builds an instance of StorageSharedKeyCredential      
    var storageSharedKeyCredential = new StorageSharedKeyCredential(<AccountName>, <AccountKey>);

SAS URI를 구축하려면 사용자 위임을 사용해야 합니다.

...
BlobServiceClient blobServiceClient = blobClient.GetParentBlobContainerClient().GetParentBlobServiceClient();

UserDelegationKey userDelegationKey = await blobServiceClient.GetUserDelegationKeyAsync
(
    DateTimeOffset.UtcNow,
    DateTimeOffset.UtcNow.AddMinutes(5d)
);
            
BlobUriBuilder blobUriBuilder = new (blobClient.Uri)
{
    // Specify the user delegation key.
    Sas = blobSasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName)
};

string uri = blobUriBuilder.ToUri();

    

상당히 많은 정보를 찾아본 결과, 이 문서에는 Microsoft의 문서가 몇 개 있습니다.https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-user-delegation-sas-create-dotnet

이 세부사항은 계정 키 대신 사용자 위임 키를 사용하여 SAS를 생성하는 것이지만 변경은 에 대한 과부하일 뿐입니다.ToSasQueryParameters()는 다른 답변과 같습니다.

이 문제를 해결하기 위해 기사의 주요 부분 몇 개입니다.먼저 BlobServiceClient를 만듭니다.

// Construct the blob endpoint from the account name.
string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", accountName);

// Create a new Blob service client with Azure AD credentials.
BlobServiceClient blobClient = new BlobServiceClient(new Uri(blobEndpoint),
                                                     new DefaultAzureCredential());

사용자 위임 키를 가져옵니다. SAS를 생성하는 데 사용됩니다.

// Get a user delegation key for the Blob service that's valid for seven days.
// You can use the key to generate any number of shared access signatures over the lifetime of the key.
UserDelegationKey key = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
                                                                   DateTimeOffset.UtcNow.AddDays(7));

마지막으로 SAS URI를 만듭니다.

// Create a SAS token that's valid for one hour.
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
    BlobContainerName = containerName,
    BlobName = blobName,
    Resource = "b",
    StartsOn = DateTimeOffset.UtcNow,
    ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
};

// Specify read permissions for the SAS.
sasBuilder.SetPermissions(BlobSasPermissions.Read);

// Use the key to get the SAS token.
string sasToken = sasBuilder.ToSasQueryParameters(key, accountName).ToString();

// Construct the full URI, including the SAS token.
UriBuilder fullUri = new UriBuilder()
{
    Scheme = "https",
    Host = string.Format("{0}.blob.core.windows.net", accountName),
    Path = string.Format("{0}/{1}", containerName, blobName),
    Query = sasToken
};

에 Azure Blob 스토리지 클라이언트 라이브러리 v12 사용.네트워크:

BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
{
    BlobContainerName = blobContainerName,
    BlobName = blobName,
    Resource = "b", //b = blob, c = container
    StartsOn = DateTimeOffset.UtcNow,
    ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(lifetimeMinutes)
};

blobSasBuilder.SetPermissions(BlobSasPermissions.Read);

StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

string sas = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString();

컨테이너에 할당된 액세스정책에 따라 공유 액세스시그니처(SAS 토큰)를 생성해야 하는 경우 다음 방법을 사용합니다.

BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
{
    BlobContainerName = blobContainerName,
    BlobName = blobName,
    Resource = "b", //b = blob, c = container
    Identifier = "ReadOnlyPolicy" //string value referees to the access policy created and assigned to the container.
};

StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

string sas = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString();

주의: SAS 토큰 생성이 컨테이너에 할당된 액세스 정책에 기반하면 BlobSasBuilder에서 에 대한 권한, 시작 시간 또는 종료 시간을 정의할 수 없습니다."액세스 정책 필드는 시그니처 또는 SAS 식별자와 관련지을 수 있지만 둘 다 관련지을 수 없습니다"라는 런타임 예외가 발생합니다.

참고 자료: https://www.craftedforeveryone.com/beginners-guide-and-reference-to-azure-blob-storage-sdk-v12-dot-net-csharp/

https://www.craftedforeveryone.com/beginners-guide-and-reference-to-azure-blob-storage-sdk-v12-dot-net-csharp/ #generate_access_policy_based_sas_contract_for_a_blob

여기: https://learn.microsoft.com/en-us/rest/api/storageservices/delegate-access-with-shared-access-signature은 Azure Storage가 다음 3가지 유형의 공유 액세스 시그니처(SAS)를 지원한다고 명시되어 있습니다.

  1. 계정 레벨 SAS (v11 SDK에서 사용하던 것)상세 및 예: https://learn.microsoft.com/en-us/azure/storage/common/storage-account-sas-create-dotnet
  2. 서비스 레벨 SAS (v12 (& V11) SDK 사용)상세 및 예: https://learn.microsoft.com/en-us/azure/storage/blobs/sas-service-create?tabs=dotnet
  3. Azure Active Directory 사용자를 사용하여 v12 SDK 사용에 대해 서명할 수 있는 Microsoft 권장 접근법인 사용자 위임 SAS.상세 및 예: https://learn.microsoft.com/en-us/azure/storage/blobs/storage-blob-user-delegation-sas-create-dotnet

1과 2는 모두 계정의 공유 키를 사용하여 SAS 토큰을 생성합니다.또한 3은 AAD 계정 사용자로부터 생성된 키를 사용하기 때문에 (이론적으로) 더 안전하고 쉽게 취소할 수 있습니다.https://learn.microsoft.com/en-us/rest/api/storageservices/create-user-delegation-sas #:~:text=Authorization%20a%20사용자%20 위임%20SAS,-When%20a%20client&text=This%20 approach%20provides%20an%20pvides%20an%20, is%20a%20security%20%best20practice를 참조하십시오.보다 안전한 이유에 대한 자세한 내용은 ('이 접근방식을 통해 보안 수준이 향상되고 계정 액세스 키를 애플리케이션 코드에 저장할 필요가 없어집니다.이러한 이유로 Azure AD 자격 증명을 사용하여 SAS를 작성하는 것이 보안 모범 사례입니다.")

현재는 스토리지 계정에서 모두 사용할 수 있지만 계정 레벨이 v12 SDK에서 구현하기 위해 지원되지 않거나(추정입니다. 견적하지 마십시오. 이것도 찾을 수 없습니다) 다른 숨겨진 방법(특히 BlobSas Builder)이 있다는 인상을 받습니다.ToSasQueryParameters() 메서드에는 오버로드가2개밖에 없습니다.이것에 의해, 유저 위임 또는 서비스 레벨의 어프로치는 실장 대상이 됩니다.

에 Azure Blob 스토리지 클라이언트 라이브러리 v12 사용.네트워크:

        BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = blobContainerName,
            BlobName = blobName,
            Resource = "b", //b = blob, c = container
            StartsOn = DateTimeOffset.UtcNow,
            ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(lifetimeMinutes)
        };

        blobSasBuilder.SetPermissions(BlobSasPermissions.Read);

        StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);

        string sas = blobSasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString();
private string BuildSASUri(BlobClient blob)
{
    // Create a user SAS that only allows reading for a minute
    BlobSasBuilder sas = new BlobSasBuilder 
    {
        BlobContainerName = blob.BlobContainerName,
        BlobName = blob.Name,
        Resource = "b",
        ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(1)
    };
    // Allow read access
    sas.SetPermissions(BlobSasPermissions.Read);
    var storageSharedKeyCredential = new StorageSharedKeyCredential(
        _iconfiguration.GetValue<string>("StorageAccount:AccountName"),
        _iconfiguration.GetValue<string>("StorageAccount:AccountKey")
    );

    return sas.ToSasQueryParameters(storageSharedKeyCredential).ToString();
}

위가 제 작업 코드입니다.

그러나 V12를 사용하여 저장된 액세스 정책을 만드는 방법을 찾을 수 없습니다.https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.blobcontainerclient.setaccesspolicy?view=azure-dotnet 입니다.

그러나 Microsoft는 BlobSignedIdentifier를 작성하는 방법을 제공하는 것을 완전히 잊은 것 같습니다.

문서가 최신이 아닙니다.https://learn.microsoft.com/en-us/azure/storage/common/storage-stored-access-policy-define-dotnet?toc=%2fazure%2fstorage%2fblobs%2ftoc.json

Microsoft 를 사용하고 있습니다.Azure. 저장소하지만 https://www.nuget.org/packages/Microsoft.Azure.Storage.Blob/에서는 더 이상 사용하지 말라고 합니다.

제 경우 솔루션은 매우 단순하고 우아한 것 같습니다.

내 이전 코드:

    using Microsoft.Azure.Storage.Blob;
    private readonly CloudBlobContainer _container;
    private Uri GetSharedAccessUri(string filename)
    {
        var blob = _container.GetBlockBlobReference(filename);
        var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
        {
            Permissions = SharedAccessBlobPermissions.Read,
            SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddYears(1)
        });
        return new Uri(blob.Uri, sas);
    }

새로운 코드:

    using Azure.Storage.Blobs;
    private readonly BlobContainerClient _container;
    private Uri GetSharedAccessUri(string filename)
    {
        var blob = _container.GetBlockBlobClient(filename);
        var sas = blob.GenerateSasUri((BlobSasPermissions)BlobContainerSasPermissions.Read, DateTime.UtcNow.AddYears(1));

        return new Uri(blob.Uri, sas);
    }

언급URL : https://stackoverflow.com/questions/59118346/how-to-get-a-shared-access-signature-on-a-blob-using-the-latest-azure-sdk-net-a