static Uri GenerateSAS() { BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, BlobName = blobname, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddHours(5) }; sasBuilder.SetPermissions(BlobSasPermissions.Read); var storageSharedKeyCredential = new StorageSharedKeyCredential(accountname, accountkey); string sasToken = sasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString(); // Build the full URI to the Blob SAS UriBuilder w_fullUri = new UriBuilder() { Scheme = "https", Host = string.Format("{0}.blob.core.windows.net", accountname), Path = string.Format("{0}/{1}", containerName, blobname), Query = sasToken }; return(w_fullUri.Uri); }
private async Task <Uri> GetServiceSasUriForBlob() { var containerClient = new BlobContainerClient(_settings.ConnectionString, _settings.ContainerName); try { await containerClient.CreateIfNotExistsAsync(); } catch (Azure.RequestFailedException ex) { if (ex.Status != 409) { throw; } } if (!containerClient.CanGenerateSasUri) { throw new NotSupportedException("cannot generate sas token"); } BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = containerClient.Name, Resource = "c" }; sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(_settings.ExpiredMunites); sasBuilder.SetPermissions(BlobSasPermissions.Create | BlobSasPermissions.Write | BlobSasPermissions.Read); return(containerClient.GenerateSasUri(sasBuilder)); }
/// <inheritdoc/> public string DownloadFileToAccessSharedUrl(string fileUrl, int urlLifeTimeInMinutes) { (string fileAccount, string fileContainer, string fileName) = ParseBlobStorageUrl(fileUrl); BlobSasBuilder blobSasBuilder = new BlobSasBuilder() { BlobContainerName = fileContainer, BlobName = fileName, Resource = "b", //b = blob, c = container StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(urlLifeTimeInMinutes) }; blobSasBuilder.SetPermissions(BlobSasPermissions.Read); string blobSasToken = GetBlobSasToken(blobSasBuilder, fileAccount); UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = $"{fileAccount}.blob.core.windows.net", Path = $"{fileContainer}/{fileName}", Query = blobSasToken }; return(fullUri.ToString()); }
private async Task <string> GetContainerSasUri(string containerName, string filename) { var blobClient = GetCloudBlobClient(); var blobReference = GetBlobReference(blobClient, containerName, filename); if (blobReference == null) { blobReference = GetDefaultBlobReference(blobClient); } //Set the expiry time and permissions for the container. //In this case no start time is specified, so the shared access signature becomes valid immediately. // we generate SAS builder var sasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, Resource = "c", ExpiresOn = DateTimeOffset.UtcNow.AddDays(1) }; // we specify permissions to only read sasBuilder.SetPermissions(BlobContainerSasPermissions.Read); //Generate the shared access signature on the container, setting the constraints directly on the signature. //var sasContainerToken = container.GetSharedAccessSignature(sasConstraints); var sasBlobToken = blobReference.GenerateSasUri(sasBuilder); //Return the URI string for the container, including the SAS token. return(blobReference.Uri + sasBlobToken.AbsoluteUri); }
public async Task SetBlobAccessTier_ContainerScoped_Basic_Convenience_ContainerSas() { await using TestScenario scenario = Scenario(); BlobClient[] blobs = await scenario.CreateBlobsAsync(3); string containerName = scenario.Containers[0].Container.Name; BlobSasBuilder blobSasBuilder = new BlobSasBuilder(BlobContainerSasPermissions.All, Recording.Now.AddDays(1)) { BlobContainerName = containerName }; BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(GetNewSharedKeyCredentials()); BlobUriBuilder blobUriBuilder = new BlobUriBuilder(scenario.Service.Uri) { BlobContainerName = containerName, Sas = sasQueryParameters }; BlobContainerClient sasContainerClient = InstrumentClient(new BlobContainerClient(blobUriBuilder.ToUri(), GetOptions())); BlobBatchClient blobBatchClient = sasContainerClient.GetBlobBatchClient(); Uri[] uris = blobs.Select(b => new Uri($"{b.Uri}?{sasQueryParameters}")).ToArray(); Response[] responses = await blobBatchClient.SetBlobsAccessTierAsync(uris, AccessTier.Cool); scenario.AssertStatus(200, responses); await scenario.AssertTiers(AccessTier.Cool, blobs); }
public async Task SetBlobAccessTier_ContainerScoped_Basic_ContainerSas() { await using TestScenario scenario = Scenario(); BlobClient[] blobs = await scenario.CreateBlobsAsync(3); string containerName = scenario.Containers[0].Container.Name; BlobSasBuilder blobSasBuilder = new BlobSasBuilder(BlobContainerSasPermissions.All, Recording.Now.AddDays(1)) { BlobContainerName = containerName }; BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(GetNewSharedKeyCredentials()); BlobUriBuilder blobUriBuilder = new BlobUriBuilder(scenario.Service.Uri) { BlobContainerName = containerName, Sas = sasQueryParameters }; BlobContainerClient sasContainerClient = InstrumentClient(new BlobContainerClient(blobUriBuilder.ToUri(), GetOptions())); BlobBatchClient blobBatchClient = sasContainerClient.GetBlobBatchClient(); using BlobBatch batch = blobBatchClient.CreateBatch(); Response[] responses = new Response[] { batch.SetBlobAccessTier(new Uri($"{blobs[0].Uri}?{sasQueryParameters}"), AccessTier.Cool), batch.SetBlobAccessTier(new Uri($"{blobs[1].Uri}?{sasQueryParameters}"), AccessTier.Cool), batch.SetBlobAccessTier(new Uri($"{blobs[2].Uri}?{sasQueryParameters}"), AccessTier.Cool) }; Response response = await blobBatchClient.SubmitBatchAsync(batch); scenario.AssertStatus(202, response); scenario.AssertStatus(200, responses); await scenario.AssertTiers(AccessTier.Cool, blobs); }
//[Authorize] // when using auth to make sure they should get the link public IActionResult Detail(string imageFileName) { var model = new ImageModel(); //validate user is authenticated before showing the image!! //get image from storage and set URL and metadata name on model var containerClient = new BlobContainerClient( config["BlobCNN"], "m3globoimages"); var blob = containerClient.GetBlobClient(imageFileName); var builder = new BlobSasBuilder { BlobContainerName = containerClient.Name, BlobName = blob.Name, ExpiresOn = DateTime.UtcNow.AddMinutes(2), Protocol = SasProtocol.Https }; builder.SetPermissions(BlobSasPermissions.Read); var uBuilder = new UriBuilder(blob.Uri) { Query = builder.ToSasQueryParameters( new Azure.Storage.StorageSharedKeyCredential( containerClient.AccountName, config["BlobKey"] )).ToString() }; model.Url = uBuilder.Uri.ToString(); model.ImageFileName = imageFileName; return(View(model)); }
private static string GetBlobSasUri(BlobContainerClient container, string blobName, StorageSharedKeyCredential key, string storedPolicyName = null) { // Create a SAS token that's valid for one hour. var sasBuilder = new BlobSasBuilder() { BlobContainerName = container.Name, BlobName = blobName, Resource = "b" }; if (storedPolicyName == null) { sasBuilder.StartsOn = DateTimeOffset.UtcNow; sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1); sasBuilder.SetPermissions(BlobContainerSasPermissions.Read); } else { sasBuilder.Identifier = storedPolicyName; } // Use the key to get the SAS token. var sasToken = sasBuilder.ToSasQueryParameters(key).ToString(); Console.WriteLine("SAS for blob is: {0}", sasToken); Console.WriteLine(); return($"{container.GetBlockBlobClient(blobName).Uri}?{sasToken}"); //return container.GetBlockBlobClient(blobName).Uri + sasToken; }
private static void FillFileInfo(File file, BlobClient blob, BlobSasBuilder readPermissions) { file.FileId = blob.Name; file.FullName = blob.Name; string[] parts = blob.Name.Split('/'); int length = parts.Length; file.Name = parts[length - 1]; file.ObjectType = parts[0]; file.ObjectId = parts[1]; string sasUrl = null; if (readPermissions != null) { sasUrl = blob.GenerateSasUri(readPermissions).ToString(); } file.Url = sasUrl ?? blob.Uri.ToString(); if (!string.IsNullOrWhiteSpace(Settings.FileSecondaryUrl)) { file.SecondaryUrl = sasUrl == null ? $"{Settings.FileSecondaryUrl}{blob.Uri.AbsolutePath}" : $"{Settings.FileSecondaryUrl}{blob.Uri.AbsolutePath}?{sasUrl.Split('?')[1]}"; } }
public string GetBlobUrl(BlobClient blobClient, bool withSasToken = false, TimeSpan tokenExpiration = default) { if (blobClient == null) { throw new AzureTableDataStoreInternalException("Unable to get URL to blob, the instance has not been initialized with a BlobClient. " + "This method is only available for LargeBlob instances instantiated or updated by TableDataStore."); } var blobUri = blobClient.Uri.ToString(); if (withSasToken) { var blobSasBuilder = new BlobSasBuilder() { BlobContainerName = blobClient.BlobContainerName, BlobName = blobClient.Name, StartsOn = DateTimeOffset.UtcNow - TimeSpan.FromMinutes(5), ExpiresOn = DateTimeOffset.UtcNow + tokenExpiration }; blobSasBuilder.SetPermissions(BlobSasPermissions.Read); var queryParams = blobSasBuilder.ToSasQueryParameters(_credential); blobUri = blobUri + "?" + queryParams.ToString(); } return(blobUri); }
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(); }
private async Task <string> GenerateSharedAccessSignature(string filePath, string storageContainerName, string storageEndpoint, string storageAccountName, string storageAccountKey, TimeSpan validUntil, bool useUserDelegation) { var now = DateTimeOffset.UtcNow; var until = now + validUntil; var builder = new BlobSasBuilder { BlobContainerName = storageContainerName, BlobName = filePath, Resource = "b", StartsOn = now.AddHours(-1), ExpiresOn = until }; builder.SetPermissions(BlobSasPermissions.Read); var token = await GenerateSasToken(builder, useUserDelegation, storageAccountName, storageAccountKey); return($"{storageEndpoint}{storageContainerName}/{filePath}?{token}"); }
/// <summary> /// We return a limited access key that allows the caller to upload a file to this specific destination for defined period of time /// </summary> private StorageEntitySas GetSharedAccessReferenceForUpload(string blobName) { var blob = blobServiceClient.GetBlobContainerClient(this.blobContainer).GetBlobClient(blobName); var storageSharedKeyCredential = new StorageSharedKeyCredential(blobServiceClient.AccountName, ConfigurationManager.AppSettings["AzureStorageEmulatorAccountKey"]); var blobSasBuilder = new BlobSasBuilder { BlobContainerName = this.blobContainer, BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5), ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5) }; policy.SetPermissions(BlobSasPermissions.Write); var sas = policy.ToSasQueryParameters(storageSharedKeyCredential).ToString(); return(new StorageEntitySas { BlobUri = blob.Uri, Credentials = sas }); }
/// <summary> /// Create a blob SAS build from Blob Object /// </summary> public static BlobSasBuilder SetBlobSasBuilder_FromBlob(BlobBaseClient blobClient, BlobSignedIdentifier signedIdentifier = null, string Permission = null, DateTime?StartTime = null, DateTime?ExpiryTime = null, string iPAddressOrRange = null, SharedAccessProtocol?Protocol = null) { BlobSasBuilder sasBuilder = SetBlobSasBuilder(blobClient.BlobContainerName, blobClient.Name, signedIdentifier, Permission, StartTime, ExpiryTime, iPAddressOrRange, Protocol); if (Util.GetVersionIdFromBlobUri(blobClient.Uri) != null) { sasBuilder.BlobVersionId = Util.GetVersionIdFromBlobUri(blobClient.Uri); } if (Util.GetSnapshotTimeFromBlobUri(blobClient.Uri) != null) { sasBuilder.Snapshot = Util.GetSnapshotTimeFromBlobUri(blobClient.Uri).Value.UtcDateTime.ToString("o"); } return(sasBuilder); }
private string GetBlobSharedAccessSignature(BlobBaseClient blob, BlobSasBuilder sasBuilder, bool generateUserDelegationSas) { if (Channel != null && Channel.StorageContext != null && Channel.StorageContext.StorageAccount.Credentials.IsSharedKey) { return(sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(Channel.StorageContext.StorageAccountName, Channel.StorageContext.StorageAccount.Credentials.ExportBase64EncodedKey())).ToString()); } if (generateUserDelegationSas) { global::Azure.Storage.Blobs.Models.UserDelegationKey userDelegationKey = null; BlobServiceClient oauthService = new BlobServiceClient(Channel.StorageContext.StorageAccount.BlobEndpoint, Channel.StorageContext.Track2OauthToken, ClientOptions); Util.ValidateUserDelegationKeyStartEndTime(sasBuilder.StartsOn, sasBuilder.ExpiresOn); userDelegationKey = oauthService.GetUserDelegationKey( startsOn: sasBuilder.StartsOn == DateTimeOffset.MinValue ? DateTimeOffset.UtcNow : sasBuilder.StartsOn.ToUniversalTime(), expiresOn: sasBuilder.ExpiresOn.ToUniversalTime(), cancellationToken: CmdletCancellationToken); return(sasBuilder.ToSasQueryParameters(userDelegationKey, blob.AccountName).ToString()); } else { throw new InvalidOperationException("Create SAS only supported with SharedKey or Oauth credentail."); } }
private Collection <File> GetFiles(FileSearchOptions searchOptions, BlobSasBuilder readPermissions) { List <File> files = new List <File>(); List <string> extensionsList = searchOptions.ExtensionsFilter == null ? new List <string>() : new List <string>(searchOptions.ExtensionsFilter); bool extensionsIsNotEmpty = extensionsList.Count > 0; var blobItems = GetBlockBlobs(Container, BlobPath, searchOptions.AllFiles); foreach (var blobItem in blobItems) { bool add = true; if (extensionsIsNotEmpty) { string extension = Path.GetExtension(blobItem.Name).ToLowerInvariant(); bool match = extensionsList.Contains(extension); add = (((!searchOptions.NegateExtensionsFilter) && match) || (searchOptions.NegateExtensionsFilter && (!match))); } if (add) { var blob = Container.GetBlobClient(blobItem.Name); File file = GetFileInfo(blob, readPermissions, blobItem.Properties); files.Add(file); } } files.Sort(CompareFilesByLastModifiedAndName); return(new Collection <File>(files)); }
public void ToSasQueryParameters_SnapshotTest() { // Arrange var constants = new TestConstants(this); var containerName = GetNewContainerName(); var blobName = GetNewBlobName(); BlobSasBuilder blobSasBuilder = BuildBlobSasBuilder(includeBlob: true, includeSnapshot: true, containerName, blobName, constants); var signature = BuildSignature(includeBlob: true, includeSnapshot: true, containerName, blobName, constants); // Act BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(constants.Sas.SharedKeyCredential); // Assert Assert.AreEqual(SasQueryParameters.DefaultSasVersion, sasQueryParameters.Version); Assert.IsNull(sasQueryParameters.Services); Assert.IsNull(sasQueryParameters.ResourceTypes); Assert.AreEqual(constants.Sas.Protocol, sasQueryParameters.Protocol); Assert.AreEqual(constants.Sas.StartTime, sasQueryParameters.StartsOn); Assert.AreEqual(constants.Sas.ExpiryTime, sasQueryParameters.ExpiresOn); Assert.AreEqual(constants.Sas.IPRange, sasQueryParameters.IPRange); Assert.AreEqual(constants.Sas.Identifier, sasQueryParameters.Identifier); Assert.AreEqual(Constants.Sas.Resource.BlobSnapshot, sasQueryParameters.Resource); Assert.AreEqual(Permissions, sasQueryParameters.Permissions); Assert.AreEqual(signature, sasQueryParameters.Signature); AssertResponseHeaders(constants, sasQueryParameters); }
private string GetContainerSASWithServicePrincipal(BlobServiceClient service, string storageAccount, string storageContainer, string blobName) { DateTimeOffset expiresOn = DateTimeOffset.UtcNow.AddHours(2); BlobSasBuilder blobSasBuilder = new BlobSasBuilder { BlobContainerName = storageContainer, ExpiresOn = DateTimeOffset.UtcNow.AddHours(2) }; blobSasBuilder.SetPermissions( BlobContainerSasPermissions.Read | BlobContainerSasPermissions.Create | BlobContainerSasPermissions.List); // the principal must have storage account level "Storage Blob Delegator" role to // be able to get user delegation key UserDelegationKey delegationKey = service.GetUserDelegationKey(null, expiresOn).Value; var sasQueryParameters = blobSasBuilder.ToSasQueryParameters(delegationKey, storageAccount); String uri = String.IsNullOrEmpty(blobName) ? String.Format("https://{0}.blob.core.windows.net/{1}?restype=container&comp=list&{2}", storageAccount, storageContainer, sasQueryParameters.ToString()) : String.Format("https://{0}.blob.core.windows.net/{1}/{2}?{3}", storageAccount, storageContainer, blobName, sasQueryParameters.ToString()); return(uri); }
private static string GetBlobSasToken(BlobBaseClient blob, AzureStorageContext context) { if (null == context.StorageAccount.Credentials || context.StorageAccount.Credentials.IsAnonymous) { return(string.Empty); } else if (context.StorageAccount.Credentials.IsSAS) { return(context.StorageAccount.Credentials.SASToken); } // SAS life time is at least 10 minutes. TimeSpan sasLifeTime = TimeSpan.FromMinutes(CopySASLifeTimeInMinutes); BlobSasBuilder sasBuilder = new BlobSasBuilder { BlobContainerName = blob.BlobContainerName, BlobName = blob.Name, ExpiresOn = DateTimeOffset.UtcNow.Add(sasLifeTime), }; if (Util.GetVersionIdFromBlobUri(blob.Uri) != null) { sasBuilder.BlobVersionId = Util.GetVersionIdFromBlobUri(blob.Uri); } sasBuilder.SetPermissions("r"); string sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(context.StorageAccountName, context.StorageAccount.Credentials.ExportBase64EncodedKey())).ToString(); if (sasToken[0] != '?') { sasToken = "?" + sasToken; } return(sasToken); }
public void ToSasQueryParameters_BlobIdentityTest() { // Arrange var constants = new TestConstants(this); var containerName = GetNewContainerName(); var blobName = GetNewBlobName(); BlobSasBuilder blobSasBuilder = BuildBlobSasBuilder(includeBlob: true, includeSnapshot: false, containerName, blobName, constants); var signature = BuildIdentitySignature(includeBlob: true, includeSnapshot: false, containerName, blobName, constants); // Act BlobSasQueryParameters sasQueryParameters = blobSasBuilder.ToSasQueryParameters(GetUserDelegationKey(constants), constants.Sas.Account); // Assert Assert.AreEqual(SasQueryParameters.DefaultSasVersion, sasQueryParameters.Version); Assert.IsNull(sasQueryParameters.Services); Assert.IsNull(sasQueryParameters.ResourceTypes); Assert.AreEqual(constants.Sas.Protocol, sasQueryParameters.Protocol); Assert.AreEqual(constants.Sas.StartTime, sasQueryParameters.StartsOn); Assert.AreEqual(constants.Sas.ExpiryTime, sasQueryParameters.ExpiresOn); Assert.AreEqual(constants.Sas.IPRange, sasQueryParameters.IPRange); Assert.AreEqual(String.Empty, sasQueryParameters.Identifier); Assert.AreEqual(constants.Sas.KeyObjectId, sasQueryParameters.KeyObjectId); Assert.AreEqual(constants.Sas.KeyTenantId, sasQueryParameters.KeyTenantId); Assert.AreEqual(constants.Sas.KeyStart, sasQueryParameters.KeyStart); Assert.AreEqual(constants.Sas.KeyExpiry, sasQueryParameters.KeyExpiry); Assert.AreEqual(constants.Sas.KeyService, sasQueryParameters.KeyService); Assert.AreEqual(constants.Sas.KeyVersion, sasQueryParameters.KeyVersion); Assert.AreEqual(Constants.Sas.Resource.Blob, sasQueryParameters.Resource); Assert.AreEqual(Permissions, sasQueryParameters.Permissions); Assert.AreEqual(signature, sasQueryParameters.Signature); AssertResponseHeaders(constants, sasQueryParameters); }
public async Task SetPermissions_BlobContainerSasPermissions(BlobContainerSasPermissions permissions) { // Arrange await using DisposingContainer test = await GetTestContainerAsync(); BlobSasBuilder blobSasBuilder = new BlobSasBuilder { StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(1), BlobContainerName = test.Container.Name }; blobSasBuilder.SetPermissions(permissions); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey); BlobUriBuilder blobUriBuilder = new BlobUriBuilder(test.Container.Uri) { Sas = blobSasBuilder.ToSasQueryParameters(sharedKeyCredential) }; BlobContainerClient sasContainerClient = new BlobContainerClient(blobUriBuilder.ToUri(), GetOptions()); // Act await foreach (BlobItem blobItem in sasContainerClient.GetBlobsAsync()) { // Just make sure the call succeeds. } }
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)))); }
private static string GetBlobSasToken(BlobBaseClient blob, AzureStorageContext context) { if (null == context.StorageAccount.Credentials || (context.StorageAccount.Credentials.IsAnonymous && !context.StorageAccount.Credentials.IsToken)) { return(string.Empty); } else if (context.StorageAccount.Credentials.IsSAS) { return(context.StorageAccount.Credentials.SASToken); } // SAS life time is at least 10 minutes. TimeSpan sasLifeTime = TimeSpan.FromMinutes(CopySASLifeTimeInMinutes); if (context.StorageAccount.Credentials.IsToken) { sasLifeTime = TimeSpan.FromMinutes(CopySASLifeTimeInMinutesOauth); } BlobSasBuilder sasBuilder = new BlobSasBuilder { BlobContainerName = blob.BlobContainerName, BlobName = blob.Name, ExpiresOn = DateTimeOffset.UtcNow.Add(sasLifeTime), }; if (Util.GetVersionIdFromBlobUri(blob.Uri) != null) { sasBuilder.BlobVersionId = Util.GetVersionIdFromBlobUri(blob.Uri); } sasBuilder.SetPermissions("rt"); string sasToken = null; if (context != null && context.StorageAccount.Credentials.IsToken) //oauth { global::Azure.Storage.Blobs.Models.UserDelegationKey userDelegationKey = null; BlobServiceClient oauthService = new BlobServiceClient(context.StorageAccount.BlobEndpoint, context.Track2OauthToken, null); Util.ValidateUserDelegationKeyStartEndTime(sasBuilder.StartsOn, sasBuilder.ExpiresOn); userDelegationKey = oauthService.GetUserDelegationKey( startsOn: sasBuilder.StartsOn == DateTimeOffset.MinValue || sasBuilder.StartsOn == null? DateTimeOffset.UtcNow : sasBuilder.StartsOn.ToUniversalTime(), expiresOn: sasBuilder.ExpiresOn.ToUniversalTime()); sasToken = sasBuilder.ToSasQueryParameters(userDelegationKey, context.StorageAccountName).ToString(); } else // sharedkey { sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(context.StorageAccountName, context.StorageAccount.Credentials.ExportBase64EncodedKey())).ToString(); } if (sasToken[0] != '?') { sasToken = "?" + sasToken; } return(sasToken); }
public async Task SasBuilderIdentifier() { string accountName = StorageAccountName; string accountKey = StorageAccountKey; string containerName = Randomize("sample-container"); string blobName = Randomize("sample-blob"); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); // setup blob var container = new BlobContainerClient(ConnectionString, containerName); try { await container.CreateAsync(); await container.GetBlobClient(blobName).UploadAsync(new MemoryStream(Encoding.UTF8.GetBytes("hello world"))); // Create one or more stored access policies. List <BlobSignedIdentifier> signedIdentifiers = new List <BlobSignedIdentifier> { new BlobSignedIdentifier { Id = "mysignedidentifier", AccessPolicy = new BlobAccessPolicy { StartsOn = DateTimeOffset.UtcNow.AddHours(-1), ExpiresOn = DateTimeOffset.UtcNow.AddDays(1), Permissions = "rw" } } }; // Set the container's access policy. await container.SetAccessPolicyAsync(permissions : signedIdentifiers); #region Snippet:SampleSnippetsBlobMigration_SasBuilderIdentifier // Create BlobSasBuilder and specify parameters BlobSasBuilder sasBuilder = new BlobSasBuilder() { Identifier = "mysignedidentifier" }; #endregion // Create full, self-authenticating URI to the resource BlobUriBuilder uriBuilder = new BlobUriBuilder(StorageAccountBlobUri) { BlobContainerName = containerName, BlobName = blobName, Sas = sasBuilder.ToSasQueryParameters(sharedKeyCredential) }; Uri sasUri = uriBuilder.ToUri(); // successful download indicates pass await new BlobClient(sasUri).DownloadToAsync(new MemoryStream()); } finally { await container.DeleteIfExistsAsync(); } }
private string GetContainerSASWithLighthouse(BlobServiceClient service, string storageAccount, string storageContainer, string blobName, StorageSharedKeyCredential credential) { BlobSasBuilder blobSasBuilder; BlobContainerClient container = service.GetBlobContainerClient(storageContainer); BlobContainerAccessPolicy policy = container.GetAccessPolicy(); BlobSignedIdentifier blobSignedIdentifier = policy.SignedIdentifiers.FirstOrDefault(x => x.Id == "expiresapr"); // if stored access policy exists, use it, otherwise, specify permissions if (blobSignedIdentifier != null) { blobSasBuilder = new BlobSasBuilder { BlobContainerName = storageContainer, Identifier = blobSignedIdentifier.Id }; /* load test how fast we can generate SAS token * for (int ii = 0; ii < 100000; ++ii ) * { * var blobSas = new BlobSasBuilder * { * BlobContainerName = storageContainer, * BlobName = "abc" + ii, * Identifier = blobSignedIdentifier.Id * }; * var param = blobSas.ToSasQueryParameters(credential).ToString(); * }*/ } else { DateTimeOffset expiresOn = DateTimeOffset.UtcNow.AddHours(2); blobSasBuilder = new BlobSasBuilder { BlobContainerName = storageContainer, ExpiresOn = expiresOn, }; blobSasBuilder.SetPermissions( BlobContainerSasPermissions.Read | BlobContainerSasPermissions.Create | BlobContainerSasPermissions.List); } var sasQueryParameters = blobSasBuilder.ToSasQueryParameters(credential).ToString(); String uri = String.IsNullOrEmpty(blobName) ? String.Format("https://{0}.blob.core.windows.net/{1}?restype=container&comp=list&{2}", storageAccount, storageContainer, sasQueryParameters.ToString()) : String.Format("https://{0}.blob.core.windows.net/{1}/{2}?{3}", storageAccount, storageContainer, blobName, sasQueryParameters.ToString()); return(uri); }
public InquiryLogBlobService(IConfiguration config, ILogger <InquiryLogBlobService> logger, BlobSasBuilder blobSasBuilder = null) { Config = config; Logger = logger; Logger.LogInformation($"{nameof(InquiryLogBlobService)} constructor"); BlobSasBuilder = blobSasBuilder ?? new BlobSasBuilder(); }
private async Task <string> GenerateSasToken(BlobSasBuilder builder, bool useUserDelegation, string storageAccountName, string storageAccountKey) { var userDelegationStart = DateTimeOffset.UtcNow.AddHours(-1); var userDelegationEnd = userDelegationStart.AddDays(3); var blobSasQueryParameters = useUserDelegation ? builder.ToSasQueryParameters(await _serviceClient.GetUserDelegationKeyAsync(userDelegationStart, userDelegationEnd), storageAccountName) : builder.ToSasQueryParameters(new StorageSharedKeyCredential(storageAccountName, storageAccountKey)); return(blobSasQueryParameters.ToString()); }
public BlobSasQueryParameters GetContainerSas( string containerName, BlobContainerSasPermissions permissions, StorageSharedKeyCredential sharedKeyCredential = default, string sasVersion = default) { BlobSasBuilder sasBuilder = GetBlobSasBuilder(containerName, sasVersion: sasVersion); sasBuilder.SetPermissions(permissions); return sasBuilder.ToSasQueryParameters(sharedKeyCredential ?? GetNewSharedKeyCredentials()); }
/// <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 async Task SetImmutibilityPolicyAsync_SetLegalHold_BlobSnapshotSas(SnapshotSasPermissions sasPermissions) { // Arrange await using DisposingImmutableStorageWithVersioningContainer vlwContainer = await GetTestVersionLevelWormContainer(TestConfigOAuth); BlobBaseClient blob = await GetNewBlobClient(vlwContainer.Container, GetNewBlobName()); Response <BlobSnapshotInfo> snapshotResponse = await blob.CreateSnapshotAsync(); BlobSasBuilder blobSasBuilder = new BlobSasBuilder { BlobContainerName = vlwContainer.Container.Name, BlobName = blob.Name, ExpiresOn = Recording.UtcNow.AddDays(1), Snapshot = snapshotResponse.Value.Snapshot }; blobSasBuilder.SetPermissions(sasPermissions); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigOAuth.AccountName, TestConfigOAuth.AccountKey); BlobUriBuilder uriBuilder = new BlobUriBuilder(blob.Uri) { Snapshot = snapshotResponse.Value.Snapshot, Sas = blobSasBuilder.ToSasQueryParameters(sharedKeyCredential) }; BlobBaseClient sasBlobSnapshotClient = InstrumentClient(new BlobBaseClient(uriBuilder.ToUri(), 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 sasBlobSnapshotClient.SetImmutabilityPolicyAsync( immutabilityPolicy : immutabilityPolicy); // Assert Assert.AreEqual(expectedImmutabilityPolicyExpiry, response.Value.ExpiresOn); Assert.AreEqual(immutabilityPolicy.PolicyMode, response.Value.PolicyMode); // Act Response <BlobLegalHoldResult> legalHoldResponse = await sasBlobSnapshotClient.SetLegalHoldAsync(hasLegalHold : false); // Assert Assert.IsFalse(legalHoldResponse.Value.HasLegalHold); await sasBlobSnapshotClient.DeleteImmutabilityPolicyAsync(); // Delete blob snapshot. await blob.WithSnapshot(snapshotResponse.Value.Snapshot).DeleteAsync(); }