/// <summary> /// Lazy Load a SasQueryParameters and cache it internally /// </summary> /// <param name="key"></param> /// <returns></returns> private SasQueryParameters GetSasQueryParameters(string key) { if (!_sasQueryParameters.ContainsKey(key)) { var csBuilder = new DbConnectionStringBuilder(); csBuilder.ConnectionString = _connectionStrings[key]; string accountName = csBuilder["AccountName"].ToString(); string accountKey = csBuilder["AccountKey"].ToString(); var keyCredential = new StorageSharedKeyCredential(accountName, accountKey); var sasBuilder = new AccountSasBuilder() { StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5), ExpiresOn = DateTimeOffset.UtcNow.AddMonths(1), Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.Object | AccountSasResourceTypes.Container }; if (key.StartsWith(SourceStorageConnectionKey)) { sasBuilder.SetPermissions(AccountSasPermissions.Read); } else if (key.StartsWith(DestinationStorageConnectionKey)) { sasBuilder.SetPermissions(AccountSasPermissions.Add | AccountSasPermissions.Create | AccountSasPermissions.Write | AccountSasPermissions.Update); } _sasQueryParameters.Add(key, sasBuilder.ToSasQueryParameters(keyCredential)); } return(_sasQueryParameters[key]); }
public async Task AccountPermissionsRawPermissions(string permissionsString) { // Arrange await using DisposingQueue test = await GetTestQueueAsync(); AccountSasBuilder accountSasBuilder = new AccountSasBuilder { StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(1), Services = AccountSasServices.Queues, ResourceTypes = AccountSasResourceTypes.All }; accountSasBuilder.SetPermissions(permissionsString); Assert.AreEqual("rwdxylacuptfi", accountSasBuilder.Permissions); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey); Uri uri = new Uri($"{test.Queue.Uri}?{accountSasBuilder.ToSasQueryParameters(sharedKeyCredential)}"); QueueClient queueClient = new QueueClient(uri, GetOptions()); // Act await queueClient.GetPropertiesAsync(); }
private string GenerateSasToken() { if (Mode == RecordedTestMode.Playback) { return(RecordedTestSanitizer.SanitizeValue); } // Create a service level SAS that only allows reading from service // level APIs AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs. Services = AccountSasServices.Blobs, // Allow access to the service level APIs. ResourceTypes = AccountSasResourceTypes.All, // Access expires in 1 hour. ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; // Allow All access sas.SetPermissions(AccountSasPermissions.All); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(TestEnvironment.AccountName, TestEnvironment.PrimaryStorageAccountKey); // return a SAS token return(sas.ToSasQueryParameters(credential).ToString()); }
public static IActionResult Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("SAS Token Requests"); var accountName = Environment.GetEnvironmentVariable("AZURE_ACCOUNT_NAME"); var key = Environment.GetEnvironmentVariable("AZURE_ACCOUNT_KEY"); var sharedKeyCredentials = new StorageSharedKeyCredential(accountName, key); var sasBuilder = new AccountSasBuilder() { StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5), Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.All, Protocol = SasProtocol.Https }; sasBuilder.SetPermissions(AccountSasPermissions.All); var sasToken = sasBuilder.ToSasQueryParameters(sharedKeyCredentials).ToString(); var storageUri = $"https://{accountName}.blob.core.windows.net/"; return(new OkObjectResult(new SasTokenDetails() { storageAccessToken = sasToken, storageUri = storageUri })); }
public void GenerateAccountSas_Builder() { var constants = new TestConstants(this); var queueEndpoint = new Uri("http://127.0.0.1/" + constants.Sas.Account); var queueSecondaryEndpoint = new Uri("http://127.0.0.1/" + constants.Sas.Account + "-secondary"); var storageConnectionString = new StorageConnectionString(constants.Sas.SharedKeyCredential, queueStorageUri: (queueEndpoint, queueSecondaryEndpoint)); string connectionString = storageConnectionString.ToString(true); AccountSasPermissions permissions = AccountSasPermissions.Read | AccountSasPermissions.Write; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); DateTimeOffset startsOn = Recording.UtcNow.AddHours(-1); AccountSasServices services = AccountSasServices.Queues; AccountSasResourceTypes resourceTypes = AccountSasResourceTypes.All; QueueServiceClient serviceClient = InstrumentClient(new QueueServiceClient(connectionString, GetOptions())); AccountSasBuilder sasBuilder = new AccountSasBuilder(permissions, expiresOn, services, resourceTypes) { StartsOn = startsOn }; // Add more properties on the builder sasBuilder.SetPermissions(permissions); // Act Uri sasUri = serviceClient.GenerateAccountSasUri(sasBuilder); // Assert AccountSasBuilder sasBuilder2 = new AccountSasBuilder(permissions, expiresOn, services, resourceTypes) { StartsOn = startsOn }; UriBuilder expectedUri = new UriBuilder(queueEndpoint); expectedUri.Query += sasBuilder.ToSasQueryParameters(constants.Sas.SharedKeyCredential).ToString(); Assert.AreEqual(expectedUri.Uri.ToString(), sasUri.ToString()); }
public void GenerateAccountSas_Builder() { TestConstants constants = TestConstants.Create(this); Uri serviceUri = new Uri($"https://{constants.Sas.Account}.queue.core.windows.net"); AccountSasPermissions permissions = AccountSasPermissions.Read | AccountSasPermissions.Write; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); AccountSasServices services = AccountSasServices.Queues; AccountSasResourceTypes resourceTypes = AccountSasResourceTypes.All; QueueServiceClient serviceClient = InstrumentClient( new QueueServiceClient( serviceUri, constants.Sas.SharedKeyCredential, GetOptions())); AccountSasBuilder sasBuilder = new AccountSasBuilder(permissions, expiresOn, services, resourceTypes); // Add more properties on the builder sasBuilder.SetPermissions(permissions); // Act Uri sasUri = serviceClient.GenerateAccountSasUri(sasBuilder); // Assert AccountSasBuilder sasBuilder2 = new AccountSasBuilder(permissions, expiresOn, services, resourceTypes); UriBuilder expectedUri = new UriBuilder(serviceUri); expectedUri.Query += sasBuilder.ToSasQueryParameters(constants.Sas.SharedKeyCredential).ToString(); Assert.AreEqual(expectedUri.Uri, sasUri); }
public async Task AccountPermissionsRawPermissions(string permissionsString) { // Arrange await using DisposingFileSystem test = await GetNewFileSystem(); AccountSasBuilder accountSasBuilder = new AccountSasBuilder { StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(1), Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.All }; await test.FileSystem.GetPropertiesAsync(); accountSasBuilder.SetPermissions(permissionsString); StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigHierarchicalNamespace.AccountName, TestConfigHierarchicalNamespace.AccountKey); Uri uri = new Uri($"{test.FileSystem.Uri}?{accountSasBuilder.ToSasQueryParameters(sharedKeyCredential)}"); DataLakeFileSystemClient sasFileSystemClient = InstrumentClient(new DataLakeFileSystemClient(uri, GetOptions())); // Act await sasFileSystemClient.GetPropertiesAsync(); }
/// <summary> /// The GetSasUri. /// </summary> /// <param name="containerName">The containerName<see cref="string"/>.</param> /// <returns>The <see cref="Task{BlobStorageRequest}"/>.</returns> public async Task <BlobStorageRequest> GetSasUri(string containerName) { // connect to our storage account and create a blob client var connectionString = SettingConfigurations.AzureWebJobsStorage; var storageAccount = CloudStorageAccount.Parse(connectionString); var blobClient = storageAccount.CreateCloudBlobClient(); StorageSharedKeyCredential credential = new StorageSharedKeyCredential(storageAccount.Credentials.AccountName, SettingConfigurations.AccountKey); // get a reference to the container var blobContainer = blobClient.GetContainerReference(containerName); await blobContainer.CreateIfNotExistsAsync(); var sasBuilder = new AccountSasBuilder() { StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddDays(7), Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.All, Protocol = SasProtocol.Https }; sasBuilder.SetPermissions(AccountSasPermissions.All); var sasToken = sasBuilder.ToSasQueryParameters(credential).ToString(); return(new BlobStorageRequest { StorageAccessToken = sasToken, StorageUri = blobContainer.ServiceClient.StorageUri.PrimaryUri.AbsoluteUri }); }
protected override async Task <string> GenerateSecret(ISecret secret, ILogger log) { log.LogInformation($"Resource Name: {secret.ResourceName}"); log.LogInformation($"Resource Group Name: {secret.ResourceGroupName}"); log.LogInformation($"Subscription Id: {secret.SubscriptionId}"); log.LogInformation($"Expires In (days): {secret.ExpiresInDays}"); var creds = new DefaultAzureCredential(includeInteractiveCredentials: true); StorageManagementClient managementClient = new StorageManagementClient(secret.SubscriptionId, creds); var accountKey = (await managementClient.StorageAccounts.ListKeysAsync(secret.ResourceGroupName, secret.ResourceName)).Value.Keys[0]; AccountSasBuilder sasBuilder = new AccountSasBuilder() { Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.Service, ExpiresOn = DateTimeOffset.UtcNow.AddDays(int.Parse(secret.ExpiresInDays)), Protocol = SasProtocol.Https, }; sasBuilder.SetPermissions(AccountSasPermissions.Read | AccountSasPermissions.Write | AccountSasPermissions.List); // Use the key to get the SAS token. string sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(secret.ResourceName, accountKey.Value)).ToString(); return(sasToken); }
private static string GetContainerSasUri(string blobname) { string StorageAccountName = System.Environment.GetEnvironmentVariable("StorageAccountName"); string StorageAccountKey = System.Environment.GetEnvironmentVariable("StorageAccountKey"); AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs Services = AccountSasServices.Blobs, // Allow access to the service level APIs ResourceTypes = AccountSasResourceTypes.All, StartsOn = DateTimeOffset.UtcNow, // Access expires in 1 hour! ExpiresOn = DateTimeOffset.UtcNow.AddDays(99999) }; sas.Protocol = SasProtocol.Https; sas.SetPermissions(AccountSasPermissions.Read); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); UriBuilder sasUri = new UriBuilder(System.Environment.GetEnvironmentVariable("BlobURI") + blobname); sasUri.Query = sas.ToSasQueryParameters(credential).ToString(); return(sasUri.Uri.AbsoluteUri); }
private static BlobServiceClient SharedAccessSignatureAuthAsync() { // Create a service level SAS that only allows reading from service // level APIs AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs Services = AccountSasServices.Blobs, // Allow access to all service level APIs ResourceTypes = AccountSasResourceTypes.All, // Specify token expiration in hours ExpiresOn = DateTimeOffset.UtcNow.AddHours(SasKeyExpiryTime) }; // Allow all access => Create, Delete, List, Process, Read, Write & Update sas.SetPermissions(AccountSasPermissions.All); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(AccountName, AccountKey); // Build a SAS URI string storageAccountUri = String.Format("https://{0}.blob.core.windows.net", AccountName); UriBuilder sasUri = new UriBuilder(storageAccountUri); sasUri.Query = sas.ToSasQueryParameters(credential).ToString(); // Create and return a service client that can authenticate with the SAS URI return(new BlobServiceClient(sasUri.Uri)); }
public IActionResult Create(FileUploadRequest request) { if (request == null) { return(this.BadRequest()); } AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs Services = AccountSasServices.Blobs, // Allow access to the service level APIs ResourceTypes = AccountSasResourceTypes.Object, // Access expires in 1 hour! ExpiresOn = DateTimeOffset.UtcNow.AddHours(1), StartsOn = DateTimeOffset.UtcNow.AddSeconds(-30) }; sas.SetPermissions(AccountSasPermissions.Write | AccountSasPermissions.Create | AccountSasPermissions.Delete); StorageSharedKeyCredential credential = new StorageSharedKeyCredential(_accountName, _key); var container = new BlobContainerClient(_connectionString, "photos"); var blob = container.GetBlobClient(request.FileName); var result = new UriBuilder(blob.Uri); result.Query = sas.ToSasQueryParameters(credential).ToString(); return(this.Ok(result.Uri.ToString())); }
public List <ResourceFile> GetResourceFiles( string containerName, string folderName) { List <ResourceFile> fileList = new List <ResourceFile>(); // Create a service level SAS that only allows reading from service // level APIs AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs Services = AccountSasServices.Blobs, // Allow access to all service level APIs ResourceTypes = AccountSasResourceTypes.All, // Specify token expiration in hours ExpiresOn = DateTimeOffset.UtcNow.AddHours(SasKeyExpiryTime) }; // Allow all access => Create, Delete, List, Process, Read, Write & Update sas.SetPermissions(AccountSasPermissions.All); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(AccountName, AccountKey); string storageAccountUri = String.Format("https://{0}.blob.core.windows.net", AccountName); BlobServiceClient blobSvcClient = new BlobServiceClient(new Uri(storageAccountUri), credential); BlobContainerClient containerClient = blobSvcClient.GetBlobContainerClient(containerName); ResourceFile file = null; // folderName is a prefix, does not need to include trailing slash '/' foreach (BlobItem blobItem in containerClient.GetBlobs(Azure.Storage.Blobs.Models.BlobTraits.None, Azure.Storage.Blobs.Models.BlobStates.None, folderName)) { BlobUriBuilder blobUri = new BlobUriBuilder(new Uri(storageAccountUri)); blobUri.BlobContainerName = containerName; blobUri.BlobName = blobItem.Name; blobUri.Query = sas.ToSasQueryParameters(credential).ToString(); file = ResourceFile.FromUrl(blobUri.ToUri().ToString(), blobItem.Name); // file.FilePath = folderName; fileList.Add(file); } ; return(fileList); }
public SasQueryParameters GetNewAccountSasCredentials(StorageSharedKeyCredential sharedKeyCredentials = default) { var builder = new AccountSasBuilder { Protocol = SasProtocol.None, Services = AccountSasServices.Files, ResourceTypes = AccountSasResourceTypes.Container, StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(+1), IPRange = new SasIPRange(IPAddress.None, IPAddress.None) }; builder.SetPermissions(AccountSasPermissions.Create | AccountSasPermissions.Delete); return(builder.ToSasQueryParameters(sharedKeyCredentials)); }
/// <summary> /// Method that generates the SAS token for Azure Blob Storage authentication /// </summary> /// <param name="key"> /// Azure account key /// </param> /// <param name="accountName"> /// Azure account name /// </param> /// <returns> /// SAS key /// </returns> public string GenerateSAS(string key, string accountName) { var sharedKeyCredentials = new StorageSharedKeyCredential(accountName, key); var sasBuilder = new AccountSasBuilder() { StartsOn = DateTimeOffset.UtcNow - TimeSpan.FromSeconds(10), ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5), Services = AccountSasServices.All, ResourceTypes = AccountSasResourceTypes.All, Protocol = SasProtocol.Https }; sasBuilder.SetPermissions(AccountSasPermissions.All); return(sasBuilder.ToSasQueryParameters(sharedKeyCredentials).ToString()); }
public async Task AccountPermissionsRawPermissions_InvalidPermission() { // Arrange await using DisposingQueue test = await GetTestQueueAsync(); AccountSasBuilder accountSasBuilder = new AccountSasBuilder { StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(1), Services = AccountSasServices.Queues, ResourceTypes = AccountSasResourceTypes.All }; TestHelper.AssertExpectedException( () => accountSasBuilder.SetPermissions("werteyfg"), new ArgumentException("e is not a valid SAS permission")); }
public object RequestUploadInfo() { var sasBuilder = new AccountSasBuilder { Services = AccountSasServices.Blobs, StartsOn = DateTimeOffset.UtcNow.AddMinutes(-5), ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(5), Protocol = SasProtocol.Https, ResourceTypes = AccountSasResourceTypes.Object | AccountSasResourceTypes.Container, }; sasBuilder.SetPermissions(AccountSasPermissions.Read | AccountSasPermissions.Write | AccountSasPermissions.Update | AccountSasPermissions.Tag); var client = new BlobServiceClient(azureOptions.CurrentValue.StorageAccount.ConnectionString); return(new { Sas = client.GenerateAccountSasUri(sasBuilder).ToString(), ContainerName = azureOptions.CurrentValue.StorageAccount.ContainerName }); }
public SasQueryParameters GetNewAccountSas( AccountSasResourceTypes resourceTypes = AccountSasResourceTypes.All, AccountSasPermissions permissions = AccountSasPermissions.All, StorageSharedKeyCredential sharedKeyCredentials = default) { var builder = new AccountSasBuilder { Protocol = SasProtocol.None, Services = AccountSasServices.Blobs, ResourceTypes = resourceTypes, StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(+1), IPRange = new SasIPRange(IPAddress.None, IPAddress.None), }; builder.SetPermissions(permissions); return(builder.ToSasQueryParameters(sharedKeyCredentials ?? GetNewSharedKeyCredentials())); }
internal SharedAccessSignatureCredentials GetAccountSasCredentials( AccountSasServices services = AccountSasServices.All, AccountSasResourceTypes resourceTypes = AccountSasResourceTypes.All, AccountSasPermissions permissions = AccountSasPermissions.All) { var sasBuilder = new AccountSasBuilder { ExpiresOn = Recording.UtcNow.AddHours(1), Services = services, ResourceTypes = resourceTypes, Protocol = SasProtocol.Https, }; sasBuilder.SetPermissions(permissions); var cred = new StorageSharedKeyCredential(TestConfigDefault.AccountName, TestConfigDefault.AccountKey); return(new SharedAccessSignatureCredentials(sasBuilder.ToSasQueryParameters(cred).ToString())); }
/// <inheritdoc /> public string CreateSharedAccessToken( CreateSharedAccessSignatureConfiguration configuration , AccountSasPermissions permissions , AccountSasResourceTypes resourceTypes , AccountSasServices services = AccountSasServices.Blobs ) { var sas = new AccountSasBuilder { ResourceTypes = resourceTypes, Services = services, StartsOn = DateTimeOffset.UtcNow.AddMinutes(-configuration.ValidFromInMinutes), ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(configuration.ValidForInMinutes + configuration.ClockScrewInMinutes) }; sas.SetPermissions(permissions); return("?" + sas.ToSasQueryParameters(this.Options.CreateStorageSharedKeyCredential())); }
public async Task SharedAccessSignatureAuthAsync() { // Create a service level SAS that only allows reading from service // level APIs AccountSasBuilder sas = new AccountSasBuilder { // Allow access to queues Services = AccountSasServices.Queues, // Allow access to the service level APIs ResourceTypes = AccountSasResourceTypes.Service, // Access expires in 1 hour! ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; // Allow read access sas.SetPermissions(AccountSasPermissions.Read); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); // Build a SAS URI UriBuilder sasUri = new UriBuilder(StorageAccountQueueUri) { Query = sas.ToSasQueryParameters(credential).ToString() }; // Create a client that can authenticate with the SAS URI QueueServiceClient service = new QueueServiceClient(sasUri.Uri); // Make a service request to verify we've succesfully authenticated await service.GetPropertiesAsync(); // Try to create a new container (which is beyond our // delegated permission) RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>( async() => await service.CreateQueueAsync(Randomize("sample-queue"))); Assert.AreEqual(403, ex.Status); }
internal string ToSasQuery(StorageSharedKeyCredential sharedKeyCredential) { if (sharedKeyCredential is null) { throw new ArgumentNullException(nameof(sharedKeyCredential)); } var sas = new AccountSasBuilder { Services = AccountSasServices.Blobs, Protocol = SasProtocol.Https, StartsOn = StartTime, ExpiresOn = ExpiryTime, ResourceTypes = AccountSasResourceTypes.All }; sas.SetPermissions((AccountSasPermissions)(int)Permissions); string query = sas.ToSasQueryParameters(sharedKeyCredential).ToString(); return(query); }
public SasQueryParameters GetNewAccountSasCredentials(StorageSharedKeyCredential sharedKeyCredentials = default) { var builder = new AccountSasBuilder { Protocol = SasProtocol.None, Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.All, StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(+1), IPRange = new SasIPRange(IPAddress.None, IPAddress.None) }; builder.SetPermissions( AccountSasPermissions.Read | AccountSasPermissions.Add | AccountSasPermissions.Create | AccountSasPermissions.Write | AccountSasPermissions.Delete | AccountSasPermissions.List); return(builder.ToSasQueryParameters(sharedKeyCredentials ?? Tenants.GetNewHnsSharedKeyCredentials())); }
/// <summary> /// Gets a URI that can be used to download a specific blob to the blob container. /// </summary> /// <param name="blob">The blob to get the download Url for.</param> /// <returns>Uri to the blob that includes the shared access key for downloading the blob.</returns> public Uri GetBlobDownloadUrl(Blob blob) { if (blob == null) { throw new ArgumentNullException(nameof(blob)); } // Create a storage shared key to use to create a shared access signature. StorageSharedKeyCredential credential = new StorageSharedKeyCredential(blob.AccountName, BlobAccountKey); // Create a service level shared access signature that only allows uploading the blob to azure blob service. AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs. Services = AccountSasServices.Blobs, // Allow access to the service level APIs. ResourceTypes = AccountSasResourceTypes.Service, // Access expires in 1 hour! ExpiresOn = DateTimeOffset.UtcNow.AddHours(1), }; // Allow read access sas.SetPermissions(AccountSasPermissions.Read); // Create a shared access signature query paramater to add to the URI that will enable the file upload. string sasToken = sas.ToSasQueryParameters(credential).ToString(); // Construct the full URI, including the SAS token. UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}.blob.core.windows.net", blob.AccountName), Path = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}/{1}", blob.ContainerName, blob.BlobName), Query = sasToken, }; return(fullUri.Uri); }
public ResourceFile GetResourceFile( string containerName, string blobName, string filePath) { // Create a service level SAS that only allows reading from service // level APIs AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs Services = AccountSasServices.Blobs, // Allow access to all service level APIs ResourceTypes = AccountSasResourceTypes.All, // Specify token expiration in hours ExpiresOn = DateTimeOffset.UtcNow.AddHours(SasKeyExpiryTime) }; // Allow all access => Create, Delete, List, Process, Read, Write & Update sas.SetPermissions(AccountSasPermissions.All); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(AccountName, AccountKey); // Build a SAS URI string storageAccountUri = String.Format("https://{0}.blob.core.windows.net", AccountName); BlobUriBuilder blobUri = new BlobUriBuilder(new Uri(storageAccountUri)); blobUri.BlobContainerName = containerName; // filePath if specified must include the trailing slash '/' string resName = filePath + blobName; blobUri.BlobName = resName; blobUri.Query = sas.ToSasQueryParameters(credential).ToString(); return(ResourceFile.FromUrl(blobUri.ToUri().ToString(), resName)); }
public void UpdateSasUri(DateTimeOffset?expiresOn = null) { var constraints = new AccountSasBuilder { Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.Service | AccountSasResourceTypes.Object, StartsOn = DateTimeOffset.UtcNow, ExpiresOn = expiresOn ?? DateTimeOffset.UtcNow.AddHours(1), Protocol = SasProtocol.Https, }; constraints.SetPermissions(AccountSasPermissions.All); var credential = new StorageSharedKeyCredential(Configuration.Storage.Name, Configuration.Storage.Key); var sasUri = new UriBuilder(BlobContainerClient.Uri) { Query = constraints.ToSasQueryParameters(credential).ToString(), }; SasUri = sasUri.Uri; }
public async Task SharedAccessSignatureAuthAsync() { // Create a service level SAS that only allows reading from service // level APIs AccountSasBuilder sas = new AccountSasBuilder { Protocol = SasProtocol.None, Services = AccountSasServices.Blobs, ResourceTypes = AccountSasResourceTypes.All, StartsOn = DateTimeOffset.UtcNow.AddHours(-1), ExpiresOn = DateTimeOffset.UtcNow.AddHours(1), IPRange = new SasIPRange(IPAddress.None, IPAddress.None) }; // Allow read access sas.SetPermissions(AccountSasPermissions.List); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); // Build a SAS URI UriBuilder sasUri = new UriBuilder(StorageAccountBlobUri); sasUri.Query = sas.ToSasQueryParameters(credential).ToString(); // Create a client that can authenticate with the SAS URI DataLakeServiceClient service = new DataLakeServiceClient(sasUri.Uri); // Make a service request to verify we've succesfully authenticated await service.GetFileSystemsAsync().FirstAsync(); // Try to create a new container (which is beyond our // delegated permission) RequestFailedException ex = Assert.ThrowsAsync <RequestFailedException>( async() => await service.CreateFileSystemAsync(Randomize("sample-filesystem"))); Assert.AreEqual(403, ex.Status); }
// </Snippet_GetServiceSasUriForBlob> #endregion //------------------------------------------------- // Get Account SAS Token //------------------------------------------------- // <Snippet_GetAccountSASToken> private static string GetAccountSASToken(StorageSharedKeyCredential key) { // Create a SAS token that's valid for one hour. AccountSasBuilder sasBuilder = new AccountSasBuilder() { Services = AccountSasServices.Blobs | AccountSasServices.Files, ResourceTypes = AccountSasResourceTypes.Service, ExpiresOn = DateTimeOffset.UtcNow.AddHours(1), Protocol = SasProtocol.Https }; sasBuilder.SetPermissions(AccountSasPermissions.Read | AccountSasPermissions.Write); // Use the key to get the SAS token. string sasToken = sasBuilder.ToSasQueryParameters(key).ToString(); Console.WriteLine("SAS token for the storage account is: {0}", sasToken); Console.WriteLine(); return(sasToken); }
public void SharedAccessSignatureAuth() { // Create a blob level SAS that allows reading change events from blob // level APIs AccountSasBuilder sas = new AccountSasBuilder { // Allow access to blobs Services = AccountSasServices.Blobs, // Allow access to the service level APIs ResourceTypes = AccountSasResourceTypes.All, // Access expires in 1 hour! ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; // Allow all access sas.SetPermissions(AccountSasPermissions.All); // Create a SharedKeyCredential that we can use to sign the SAS token StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey); // Build a SAS URI UriBuilder sasUri = new UriBuilder(StorageAccountBlobUri); sasUri.Query = sas.ToSasQueryParameters(credential).ToString(); // Create a client that can authenticate with the SAS URI BlobChangeFeedClient service = new BlobChangeFeedClient(sasUri.Uri); List <BlobChangeFeedEvent> changeFeedEvents = new List <BlobChangeFeedEvent>(); // Make a service request to verify we've successfully authenticated foreach (BlobChangeFeedEvent changeFeedEvent in service.GetChanges()) { changeFeedEvents.Add(changeFeedEvent); } }
public void GenerateAccountSas_WrongService_Service() { TestConstants constants = TestConstants.Create(this); Uri serviceUri = new Uri($"https://{constants.Sas.Account}.dfs.core.windows.net"); AccountSasPermissions permissions = AccountSasPermissions.Read | AccountSasPermissions.Write; DateTimeOffset expiresOn = Recording.UtcNow.AddHours(+1); AccountSasServices services = AccountSasServices.Files; // Wrong Service AccountSasResourceTypes resourceTypes = AccountSasResourceTypes.All; DataLakeServiceClient serviceClient = InstrumentClient(new DataLakeServiceClient( serviceUri, constants.Sas.SharedKeyCredential, GetOptions())); AccountSasBuilder sasBuilder = new AccountSasBuilder(permissions, expiresOn, services, resourceTypes); // Add more properties on the builder sasBuilder.SetPermissions(permissions); // Act TestHelper.AssertExpectedException( () => serviceClient.GenerateAccountSasUri(sasBuilder), new InvalidOperationException("SAS Uri cannot be generated. builder.Services does specify Blobs. builder.Services must either specify Blobs or specify all Services are accessible in the value.")); }