public async Task SetPermissions_BlobSasPermissions(BlobSasPermissions permissions) { // Arrange await using DisposingContainer test = await GetTestContainerAsync(); BlobBaseClient blob = await GetNewBlobClient(test.Container); BlobSasBuilder blobSasBuilder = new BlobSasBuilder { StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(1), BlobContainerName = test.Container.Name, BlobName = blob.Name }; blobSasBuilder.SetPermissions(permissions); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey); BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blob.Uri) { Sas = blobSasBuilder.ToSasQueryParameters(sharedKeyCredential) }; BlobBaseClient sasBlobClient = InstrumentClient(new BlobBaseClient(blobUriBuilder.ToUri(), GetOptions())); // Act await sasBlobClient.ExistsAsync(); }
public string GenerateBlobSasUri(string containerName, string blobName, BlobSasPermissions permissions, DateTimeOffset expiresOn, string storedPolicyName = "") { var message = ""; var containerClient = GetBlobContainerClient(containerName); var blobClient = containerClient.GetBlobClient(blobName); if (!blobClient.CanGenerateSasUri) { message = "Could not generate the SAS uri."; throw new ApiHttpStatusException <ErrorModel <int> >(HttpStatusCode.BadRequest, message, new ErrorModel <int> { Code = (int)HttpStatusCode.NotAcceptable, Message = message, }); } var builder = new BlobSasBuilder(permissions, expiresOn) { BlobContainerName = blobClient.BlobContainerName, BlobName = blobClient.Name, Resource = "b", }; if (!string.IsNullOrWhiteSpace(storedPolicyName)) { builder = new BlobSasBuilder(); builder.Identifier = storedPolicyName; } var sasUri = blobClient.GenerateSasUri(builder); return(sasUri.ToString()); }
public async Task SetImmutibilityPolicyAsync_SetLegalHold_BlobSas(BlobSasPermissions sasPermissions) { // Arrange BlobBaseClient blob = await GetNewBlobClient(_containerClient, GetNewBlobName()); BlobBaseClient sharedKeyBlob = InstrumentClient( BlobsClientBuilder.GetServiceClient_OAuthAccount_SharedKey() .GetBlobContainerClient(_containerClient.Name) .GetBlobBaseClient(blob.Name)); Uri blobSasUri = sharedKeyBlob.GenerateSasUri(sasPermissions, Recording.UtcNow.AddDays(1)); BlobBaseClient sasBlobClient = InstrumentClient(new BlobBaseClient(blobSasUri, GetOptions())); BlobImmutabilityPolicy immutabilityPolicy = new BlobImmutabilityPolicy { ExpiresOn = Recording.UtcNow.AddMinutes(5), PolicyMode = BlobImmutabilityPolicyMode.Unlocked }; // The service rounds Immutability Policy Expiry to the nearest second. DateTimeOffset expectedImmutabilityPolicyExpiry = RoundToNearestSecond(immutabilityPolicy.ExpiresOn.Value); // Act Response <BlobImmutabilityPolicy> response = await sasBlobClient.SetImmutabilityPolicyAsync( immutabilityPolicy : immutabilityPolicy); // Assert Assert.AreEqual(expectedImmutabilityPolicyExpiry, response.Value.ExpiresOn); Assert.AreEqual(immutabilityPolicy.PolicyMode, response.Value.PolicyMode); // Act Response <BlobLegalHoldResult> legalHoldResponse = await sasBlobClient.SetLegalHoldAsync(hasLegalHold : false); // Assert Assert.IsFalse(legalHoldResponse.Value.HasLegalHold); }
/// <summary> /// Generate a Url to a blob to redirect to with a user delegation sas token. /// </summary> /// <param name="blobName">Name of blob to redirect to (blob storage name rather than original file name).</param> /// <param name="downloadPermissions">Permissions to be applied to the SasBuilder.</param> /// <returns></returns> public async Task <string> GetRelativeDownloadUrlAsync(string blobName, BlobSasPermissions downloadPermissions, CancellationToken cancellationToken) { if (string.IsNullOrWhiteSpace(blobName)) { throw new ArgumentNullException(nameof(blobName)); } if (string.IsNullOrWhiteSpace(_configurationProvider.FileDownloadEndpoint)) { throw new ArgumentNullException(nameof(_configurationProvider.FileDownloadEndpoint)); } // Set the blob service client BlobServiceClient blobServiceClient = new BlobServiceClient(new Uri(_configurationProvider.FileDownloadEndpoint), new DefaultAzureCredential()); // Generate the user delegation key - get from cache if available or add to cache on generation var userDelegationKey = await _memoryCache.GetOrCreateAsync( Constants.Constants.BlobStorageDownloadUserDelegationKeyCacheKey, async cacheEntry => { cacheEntry.Priority = CacheItemPriority.High; cacheEntry.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(23); var azureResponse = await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(1), cancellationToken); return(azureResponse.Value); }); if (userDelegationKey != null) { BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = _configurationProvider.FileContainerName, BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(40) }; // Specify read and write permissions for the SAS. Pass these in? sasBuilder.SetPermissions(downloadPermissions); // Add the SAS token to the blob URI. BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobServiceClient.Uri) { // Set container and blob name BlobContainerName = _configurationProvider.FileContainerName, BlobName = blobName, // Specify the user delegation key. Sas = sasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName) }; // Build the blob redirect path required return($"{blobUriBuilder.BlobContainerName}/{blobUriBuilder.BlobName}?{blobUriBuilder.Sas}"); } throw new ApplicationException("Unable to generate download token"); }
public BlobSasQueryParameters GetBlobSas( string containerName, string blobName, BlobSasPermissions permissions, StorageSharedKeyCredential sharedKeyCredential = default, string sasVersion = default) { BlobSasBuilder sasBuilder = GetBlobSasBuilder(containerName, blobName, sasVersion: sasVersion); sasBuilder.SetPermissions(permissions); return sasBuilder.ToSasQueryParameters(sharedKeyCredential ?? GetNewSharedKeyCredentials()); }
public BlobSasQueryParameters GetBlobIdentitySas( string containerName, string blobName, BlobSasPermissions permissions, UserDelegationKey userDelegationKey, string accountName, string sasVersion = default) { BlobSasBuilder sasBuilder = GetBlobSasBuilder(containerName, blobName, sasVersion: sasVersion); sasBuilder.SetPermissions(permissions); return sasBuilder.ToSasQueryParameters(userDelegationKey, accountName); }
public static string CreateSASToken(string BlobStorageAccountName, string BlobStorageContainerName, string BlobStorageFolderPath, string DataFileName, int accessDuration) { // Get a credential and create a client object for the blob container. Note using new Azure Core credential flow BlobServiceClient blobClient = new BlobServiceClient(new Uri(BlobStorageAccountName), new DefaultAzureCredential()); //blobClient.GetProperties(); var startDate = DateTimeOffset.UtcNow.AddMinutes(-1); var endDate = DateTimeOffset.UtcNow.AddDays(accessDuration); // 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 = blobClient.GetUserDelegationKey(startDate, endDate); Uri BlobUri = new Uri(BlobStorageAccountName); BlobContainerClient containerClient = new BlobContainerClient(BlobUri, new DefaultAzureCredential()); // Create a SAS token BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = BlobStorageContainerName, BlobName = String.Format("{0}{1}", BlobStorageFolderPath, DataFileName), Resource = "b", StartsOn = startDate, ExpiresOn = endDate, Protocol = SasProtocol.Https }; // Specify read permissions for the SAS. BlobSasPermissions perms = BlobSasPermissions.Create | BlobSasPermissions.Write; sasBuilder.SetPermissions(perms); // Use the key to get the SAS token. string sasToken = sasBuilder.ToSasQueryParameters(key, BlobUri.Host.Split('.')[0]).ToString(); // Construct the full URI, including the SAS token. UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = string.Format("{0}.blob.core.windows.net", BlobUri.Host.Split('.')[0]), Path = string.Format("{0}/{1}{2}", BlobStorageContainerName, BlobStorageFolderPath, DataFileName), Query = sasToken }; string retvar = "&Path=" + Uri.EscapeDataString(fullUri.Path.ToString()); retvar += "&" + sasToken; return(retvar); }
public Uri?GetContainerSasUrlService( BlobContainerClient client, BlobSasPermissions permissions, bool tag = false, TimeSpan?timeSpan = null) { var(start, expiry) = SasTimeWindow(timeSpan ?? TimeSpan.FromDays(30.0)); var sasBuilder = new BlobSasBuilder(permissions, expiry) { StartsOn = start }; var sas = client.GenerateSasUri(sasBuilder); return(sas); }
public BlobSasTokenDto GenerateSasForBlob(string blobId, TimeSpan expiresIn, BlobSasPermissions permission) { var policy = new SharedAccessBlobPolicy(); policy.Permissions = (SharedAccessBlobPermissions)permission; policy.SharedAccessExpiryTime = DateTime.UtcNow.Add(expiresIn); var blob = GetBlobReference(blobId); var sasToken = blob.GetSharedAccessSignature(policy); return(new BlobSasTokenDto { BlobUri = blob.Uri.ToString(), SasToken = sasToken }); }
public string GetSasUriForBlob(BlockBlobClient blob, BlobSasPermissions blobSasPermissions) { // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); BlobSasBuilder sasBuilder = new BlobSasBuilder { StartsOn = DateTime.UtcNow.AddMinutes(-5), // to allow for clock skew ExpiresOn = DateTime.UtcNow.AddHours(24), }; sasBuilder.SetPermissions(blobSasPermissions); // Build a URI + SASToken string UriBuilder sasUri = new UriBuilder(blob.Uri) { Query = sasBuilder.ToSasQueryParameters(credential).ToString() }; return(sasUri.Uri.AbsoluteUri); }
async Task <Uri> ISharedUriAccessible.GetSharedUriAsync(string name, string partition, AccessPermissions permissions, DateTimeOffset?startTime, DateTimeOffset?expiryTime, CancellationToken cancellationToken) { BlobSasPermissions sasPermissions = default; if (permissions.HasFlagSet(AccessPermissions.Read)) { sasPermissions |= BlobSasPermissions.Read; } if (permissions.HasFlagSet(AccessPermissions.Write)) { sasPermissions |= BlobSasPermissions.Write; } if (permissions.HasFlagSet(AccessPermissions.Delete)) { sasPermissions |= BlobSasPermissions.Delete; } return(await GetSharedAccessUriAsync(name, partition, sasPermissions, startTime, expiryTime, cancellationToken : cancellationToken).ConfigureAwait(false)); }
public async Async.Task <Uri> GetFileSasUrl(Container container, string name, StorageType storageType, BlobSasPermissions permissions, TimeSpan?duration = null) { var client = await FindContainer(container, storageType) ?? throw new Exception($"unable to find container: {container.ContainerName} - {storageType}"); var(startTime, endTime) = SasTimeWindow(duration ?? TimeSpan.FromDays(30)); var sasBuilder = new BlobSasBuilder(permissions, endTime) { StartsOn = startTime, BlobContainerName = _config.OneFuzzStoragePrefix + container.ContainerName, BlobName = name }; var sasUrl = client.GetBlobClient(name).GenerateSasUri(sasBuilder); return(sasUrl); }
private Task <RepositoryResult <(string link, DateTimeOffset validUntil)> > GeSasLinkInternalAsync(string filePath, string container, int validForMinutes, BlobSasPermissions permissions, string friendlyFileName) { // Taken from the docs at // https://docs.microsoft.com/en-us/azure/storage/blobs/storage-blob-user-delegation-sas-create-dotnet if (validForMinutes <= 0) { return(Task.FromResult(RepositoryResult <(string, DateTimeOffset)> .Fail("The validity in minutes must be greater than zero"))); } var validUntil = DateTimeOffset.UtcNow.AddMinutes(validForMinutes); var sasBuilder = new BlobSasBuilder() { BlobContainerName = container, BlobName = filePath, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = validUntil, }; if (!string.IsNullOrWhiteSpace(friendlyFileName)) { sasBuilder.ContentDisposition = new ContentDisposition { DispositionType = "attachment", FileName = friendlyFileName }.ToString(); } else { try { var fileName = Path.GetFileName(filePath); sasBuilder.ContentDisposition = new ContentDisposition { DispositionType = "attachment", FileName = fileName }.ToString(); } catch { /* We're ignoring the case where a non-valid file name was given */ } } sasBuilder.SetPermissions(permissions); var key = new StorageSharedKeyCredential(_blobClient.AccountName, _accessKey); // Construct the full URI, including the SAS token. var blobReference = GetBlobReference(container, filePath); var blobUri = new BlobUriBuilder(blobReference.Uri) { // Use the key to get the SAS token. Sas = sasBuilder.ToSasQueryParameters(key), BlobContainerName = container, BlobName = filePath, } .ToUri(); return(Task.FromResult(RepositoryResult <(string, DateTimeOffset)> .Success((blobUri.ToString(), validUntil)))); }
public static async Task <Uri> GetUserDelegationSasBlobAsync(this BlobServiceClient self, string containerName, string blobName, BlobSasPermissions permissions = BlobSasPermissions.Read, uint durationMinutes = 10) { var key = await self.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow.AddMinutes(-5), DateTimeOffset.UtcNow.AddDays(6)); // max is 7 days var sasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5), ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(durationMinutes) }; sasBuilder.SetPermissions(permissions); var sasToken = sasBuilder.ToSasQueryParameters(key, self.AccountName).ToString(); var fullUri = new UriBuilder() { Scheme = "https", Host = $"{self.AccountName}.blob.core.windows.net", Path = $"{containerName}/{blobName}", Query = sasToken }; return(fullUri.Uri); }
private Uri MakePreAuthenticatedUrl(string oid, BlobSasPermissions permissions) { var blob = _client.GetBlobClient(GetBlobName(oid)); return(blob.GenerateSasUri(permissions, GetExpiry())); }
public async Task <Uri> GetSharedAccessUriAsync(string blobName, string directoryRelativeAddress = null, BlobSasPermissions permissions = BlobSasPermissions.Read, DateTimeOffset?startTime = null, DateTimeOffset?expiryTime = null, CancellationToken cancellationToken = default) { ArgCheck.NotNullOrEmpty(nameof(blobName), blobName); directoryRelativeAddress ??= _defaultDirectoryRelativeAddress; startTime ??= DateTimeOffset.UtcNow.AddMinutes(-5); expiryTime ??= DateTimeOffset.UtcNow.Add(_defaultSharedAccessDuration); var blobClient = GetBlobClient(blobName, directoryRelativeAddress); var sasBuilder = new BlobSasBuilder() { BlobContainerName = blobClient.BlobContainerName, BlobName = blobClient.Name, Resource = "b", StartsOn = startTime.Value, ExpiresOn = expiryTime.Value, Protocol = SasProtocol.Https, }; sasBuilder.SetPermissions(permissions); if (blobClient.CanGenerateSasUri) { return(CleanUpUri(blobClient.GenerateSasUri(sasBuilder))); } if (_storageSharedKeyCredential != null) { return(CleanUpUri(new BlobUriBuilder(blobClient.Uri) { Sas = sasBuilder.ToSasQueryParameters(_storageSharedKeyCredential), }.ToUri())); } if (_useManagedIdentity) { var userDelegationKey = (await _accountClient.GetUserDelegationKeyAsync(null, expiryTime.Value, cancellationToken).ConfigureAwait(false)).Value; return(CleanUpUri(new BlobUriBuilder(blobClient.Uri) { Sas = sasBuilder.ToSasQueryParameters(userDelegationKey, blobClient.AccountName), }.ToUri())); } throw new InvalidOperationException("Must use Shared Account Key or Token Credentials (including Managed Identity) assigned the Storage Blob Delegator role to generate a Shared Access Signature (SAS)."); }