public BlobSasQueryParameters GetNewBlobServiceSasCredentialsBlob(string containerName, string blobName, StorageSharedKeyCredential sharedKeyCredentials = default)
        {
            BlobSasBuilder builder = GetBlobSasBuilder(containerName, blobName);

            builder.SetPermissions(
                BlobSasPermissions.Read |
                BlobSasPermissions.Add |
                BlobSasPermissions.Create |
                BlobSasPermissions.Delete |
                BlobSasPermissions.Write);
            return(builder.ToSasQueryParameters(sharedKeyCredentials ?? GetNewSharedKeyCredentials()));
        }
        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()));
        }
Пример #3
0
        public async Task SetImmutibilityPolicyAsync_SetLegalHold_BlobSnapshotSas(SnapshotSasPermissions sasPermissions)
        {
            // Arrange
            BlobBaseClient blob = await GetNewBlobClient(_containerClient, GetNewBlobName());

            Response <BlobSnapshotInfo> snapshotResponse = await blob.CreateSnapshotAsync();

            BlobSasBuilder blobSasBuilder = new BlobSasBuilder
            {
                BlobContainerName = _containerClient.Name,
                BlobName          = blob.Name,
                ExpiresOn         = Recording.UtcNow.AddDays(1),
                Snapshot          = snapshotResponse.Value.Snapshot
            };

            blobSasBuilder.SetPermissions(sasPermissions);
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(Tenants.TestConfigOAuth.AccountName, Tenants.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();
        }
Пример #4
0
 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 async Task <IActionResult> GenerateSasToken(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)]
            HttpRequest req, ILogger log, ExecutionContext context)
        {
            log.LogWarning($"HTTP trigger function {nameof(GetSasToken)} received a request.");

            ApiAuthorizationResult authorizationResult = await _apiAuthorization.AuthorizeAsync(req.Headers);

            if (authorizationResult.Failed)
            {
                log.LogWarning(authorizationResult.FailureReason);
                return(new UnauthorizedResult());
            }
            log.LogWarning($"HTTP trigger function {nameof(GetSasToken)} request is authorized.");

            string    requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            ImageData imageData   = JsonConvert.DeserializeObject <ImageData>(requestBody);

            CloudStorageAccount storageAccount = GetCloudStorageAccount(context);
            var credentials = storageAccount.Credentials;
            var accountName = credentials.AccountName;
            var accountKey  = credentials.ExportBase64EncodedKey();

            var fullFileName = GetFullFileName(imageData.SasAccessType);
            var blobNamePath = GetBlobNamePath(imageData.SasAccessType);
            var blobName     = $"{blobNamePath}/{fullFileName}";

            // Create an instance of the CloudBlobClient
            CloudBlobClient client = storageAccount.CreateCloudBlobClient();

            // Retrieve an instance of the container using hard-code container name
            CloudBlobContainer container = client.GetContainerReference("cdn");

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

            // Specify permission for the SAS
            sasBuilder.SetPermissions(BlobSasPermissions.Create);

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

            var sasUri = $"{container.GetBlobReference(blobName).Uri}?{sasToken}";

            return(new OkObjectResult(sasUri));
        }
Пример #6
0
 private string GetBlobSasUri(BlobClient blobClient, BlobSasBuilder sasBuilder, string container)
 {
     return(new UriBuilder
     {
         Scheme = _storageOptions.ContentScheme,
         Host = _storageOptions.ContentHostname,
         Path = $"{container}/{blobClient.Name}",
         Query = sasBuilder
                 .ToSasQueryParameters(new StorageSharedKeyCredential(_storageOptions.Account, _storageOptions.Key))
                 .ToString()
     }.ToString());
 }
        private async Task <Uri> GetUserDelegationSasBlobUri(string blobName)
        {
            // Construct the blob endpoint from the account name.
            var blobEndpoint = $"https://{_config["StorageAccount:Name"]}.blob.core.windows.net";

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

            // Get a user delegation key for the Blob service that's valid for 10 minutes.
            // 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.AddMinutes(10));

            // Read the key's properties.
            _logger.LogInformation("User delegation key properties:");
            _logger.LogInformation("Key signed start: {0}", key.SignedStartsOn);
            _logger.LogInformation("Key signed expiry: {0}", key.SignedExpiresOn);
            _logger.LogInformation("Key signed object ID: {0}", key.SignedObjectId);
            _logger.LogInformation("Key signed tenant ID: {0}", key.SignedTenantId);
            _logger.LogInformation("Key signed service: {0}", key.SignedService);
            _logger.LogInformation("Key signed version: {0}", key.SignedVersion);

            // Create a SAS token that's valid for one hour.
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = _config["StorageAccount:ContainerName"],
                BlobName          = blobName,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow,
                ExpiresOn         = DateTimeOffset.UtcNow.AddMinutes(10)
            };

            // Specify write permissions for the SAS.
            sasBuilder.SetPermissions(BlobSasPermissions.Write);

            // Use the key to get the SAS token.
            var sasToken = sasBuilder.ToSasQueryParameters(key, _config["StorageAccount:Name"]).ToString();

            // Construct the full URI, including the SAS token.
            var fullUri = new UriBuilder()
            {
                Scheme = "https",
                Host   = $"{_config["StorageAccount:Name"]}.blob.core.windows.net",
                Path   = $"{_config["StorageAccount:ContainerName"]}/{blobName}",
                Query  = sasToken
            };

            _logger.LogInformation("User delegation SAS URI: {0}", fullUri);

            return(fullUri.Uri);
        }
Пример #8
0
        private string GetBlobSasUri(string uri)
        {
            var adHocSAS = new BlobSasBuilder
            {
                BlobContainerName = this.containerName,
                ExpiresOn         = DateTime.UtcNow.AddHours(1),
            };

            adHocSAS.SetPermissions(BlobSasPermissions.All);
            var sasToken = adHocSAS.ToSasQueryParameters(new Azure.Storage.StorageSharedKeyCredential(this.accountName, this.accountKey));

            return(uri + sasToken);
        }
Пример #9
0
        public async Task SetImmutibilityPolicyAsync_SetLegalHold_BlobVersionSas(BlobVersionSasPermissions sasPermissions)
        {
            // Arrange
            await using DisposingImmutableStorageWithVersioningContainer vlwContainer = await GetTestVersionLevelWormContainer(TestConfigOAuth);

            BlobBaseClient blob = await GetNewBlobClient(vlwContainer.Container, GetNewBlobName());

            IDictionary <string, string> metadata         = BuildMetadata();
            Response <BlobInfo>          metadataResponse = await blob.SetMetadataAsync(metadata);

            BlobSasBuilder blobSasBuilder = new BlobSasBuilder
            {
                BlobContainerName = vlwContainer.Container.Name,
                BlobName          = blob.Name,
                ExpiresOn         = Recording.UtcNow.AddDays(1),
                Version           = metadataResponse.Value.VersionId
            };

            blobSasBuilder.SetPermissions(sasPermissions);
            StorageSharedKeyCredential sharedKeyCredential = new StorageSharedKeyCredential(TestConfigOAuth.AccountName, TestConfigOAuth.AccountKey);
            BlobUriBuilder             uriBuilder          = new BlobUriBuilder(blob.Uri)
            {
                VersionId = metadataResponse.Value.VersionId,
                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);
        }
Пример #10
0
        /// <inheritdoc/>
        public string GetSasUrlForBlob(Uri blobUri, TimeSpan ttl, StorageClientProviderContext context)
        {
            _ = blobUri ?? throw new ArgumentNullException(nameof(blobUri));
            _ = context ?? throw new ArgumentNullException(nameof(context));

            try
            {
                var blobUriBuilder = new BlobUriBuilder(blobUri);

                // Create a SAS token that's valid for the TimeSpan, plus a back-off start for clock skew.
                var            timeRange  = StorageHelpers.CreateTimeRangeForUrl(ttl);
                BlobSasBuilder sasBuilder = new BlobSasBuilder
                {
                    BlobContainerName = blobUriBuilder.BlobContainerName,
                    BlobName          = blobUriBuilder.BlobName,
                    Resource          = "b", // "b" is for blob
                    StartsOn          = timeRange.StartTime,
                    ExpiresOn         = timeRange.EndTime,
                }.UnescapeTargetPath();                             // Important adjustment(s) for SAS computation

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

                var sleeve         = _blobBaseClientProvider.GetBlobClientSleeveForUri(blobUri, context);
                var userDelegation = sleeve.Service.GetUserDelegationKey(sasBuilder.StartsOn, sasBuilder.ExpiresOn)?.Value;

                if (userDelegation == null)
                {
                    var msg = $@"Unable to get a user delegation key from the Storage service for blob {blobUri}";
                    _log.LogEvent(LogEventIds.StorageServiceMissingConnectionString, msg);
                    throw new GridwichStorageServiceException(blobUri, msg, LogEventIds.StorageServiceMissingConnectionString, context.ClientRequestIdAsJObject);
                }

                var sasToken = sasBuilder.ToSasQueryParameters(userDelegation, blobUriBuilder.AccountName);
                blobUriBuilder.Sas = sasToken;

                // Construct the full URI, including the SAS token. AbsoluteUri (vs. ToString) is to ensure the %HH escaping is used.
                return(blobUriBuilder.ToUri().AbsoluteUri);
            }
            catch (RequestFailedException e)
            {
                var msg = $@"Unable to get a user delegation key from the Storage service for blob {blobUri}";
                _log.LogEvent(LogEventIds.StorageServiceMissingConnectionString, msg);
                throw new GridwichStorageServiceException(blobUri, msg, LogEventIds.StorageServiceMissingConnectionString, context.ClientRequestIdAsJObject, e);
            }
            catch (Exception e)
            {
                _log.LogExceptionObject(LogEventIds.FailedToCreateBlobSasUriInStorageService, e, blobUri);
                throw new GridwichStorageServiceException(blobUri, "Failed to generate the SAS url.",
                                                          LogEventIds.FailedToCreateBlobSasUriInStorageService, context.ClientRequestIdAsJObject, e);
            }
        }
        private string GetSasToken(string containerName, string blobName, string resourceType, BlobAccountSasPermissions permissions, DateTimeOffset startsOn, DateTimeOffset expiresOn)
        {
            var sasBuilder = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                BlobName          = blobName,
                Resource          = resourceType,
                StartsOn          = startsOn,
                ExpiresOn         = expiresOn
            };

            sasBuilder.SetPermissions(permissions);
            return(sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(_accountName, _accountKey)).ToString());
        }
Пример #12
0
        public string GetServiceSASToken()
        {
            Logger.LogInformation($"{nameof(InquiryLogBlobService)} {nameof(GetServiceSASToken)}");
            BlobSasBuilder.BlobContainerName = Config.InquiryLogBlobStorageContainerPrefix().ToLower();
            BlobSasBuilder.Resource          = "c";
            BlobSasBuilder.StartsOn          = DateTimeOffset.UtcNow;
            BlobSasBuilder.ExpiresOn         = DateTimeOffset.UtcNow.AddMinutes(10);
            BlobSasBuilder.SetPermissions(BlobContainerSasPermissions.Create);

            var credential = new StorageSharedKeyCredential(Config.InquiryLogBlobAccountName(), Config.InquiryLogBlobAccountKey());
            var sasToken   = BlobSasBuilder.ToSasQueryParameters(credential).ToString();

            return(sasToken);
        }
        private async Task <bool> DoesOAuthWorkAsync()
        {
            TestContext.Error.WriteLine($"Blob Probing OAuth {Process.GetCurrentProcess().Id}");

            try
            {
                for (int i = 0; i < 10; i++)
                {
                    BlobServiceClient serviceClient = new BlobServiceClient(
                        new Uri(TestConfigurations.DefaultTargetOAuthTenant.BlobServiceEndpoint),
                        GetOAuthCredential(TestConfigurations.DefaultTargetOAuthTenant));
                    await serviceClient.GetPropertiesAsync();

                    var containerName   = Guid.NewGuid().ToString();
                    var containerClient = serviceClient.GetBlobContainerClient(containerName);
                    await containerClient.CreateIfNotExistsAsync();

                    try
                    {
                        await containerClient.GetPropertiesAsync();

                        var blobName   = Guid.NewGuid().ToString();
                        var blobClient = containerClient.GetAppendBlobClient(blobName);
                        await blobClient.CreateIfNotExistsAsync();

                        await blobClient.GetPropertiesAsync();

                        var userDelegationKey = await serviceClient.GetUserDelegationKeyAsync(startsOn : null, expiresOn : DateTimeOffset.UtcNow.AddHours(1));

                        var sasBuilder = new BlobSasBuilder(BlobSasPermissions.All, DateTimeOffset.UtcNow.AddHours(1))
                        {
                            BlobContainerName = containerName,
                            BlobName          = blobName,
                        };
                        var sas = sasBuilder.ToSasQueryParameters(userDelegationKey.Value, serviceClient.AccountName).ToString();
                        await new BlobBaseClient(blobClient.Uri, new AzureSasCredential(sas)).GetPropertiesAsync();
                    }
                    finally
                    {
                        await containerClient.DeleteIfExistsAsync();
                    }
                }
            } catch (RequestFailedException e) when(e.Status == 403 && e.ErrorCode == "AuthorizationPermissionMismatch")
            {
                TestContext.Error.WriteLine($"Blob Probing OAuth - not ready {Process.GetCurrentProcess().Id}");
                return(false);
            }
            TestContext.Error.WriteLine($"Blob Probing OAuth - ready {Process.GetCurrentProcess().Id}");
            return(true);
        }
Пример #14
0
        public BlobSasQueryParameters GetNewBlobServiceSasCredentialsContainer(string containerName, StorageSharedKeyCredential sharedKeyCredentials = default)
        {
            var builder = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                Protocol          = SasProtocol.None,
                StartsOn          = Recording.UtcNow.AddHours(-1),
                ExpiresOn         = Recording.UtcNow.AddHours(+1),
                IPRange           = new SasIPRange(IPAddress.None, IPAddress.None)
            };

            builder.SetPermissions(BlobContainerSasPermissions.All);
            return(builder.ToSasQueryParameters(sharedKeyCredentials ?? GetNewSharedKeyCredentials()));
        }
Пример #15
0
        public BlobSasQueryParameters GetNewBlobServiceIdentitySasCredentialsContainer(string containerName, UserDelegationKey userDelegationKey, string accountName)
        {
            var builder = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                Protocol          = SasProtocol.None,
                StartsOn          = Recording.UtcNow.AddHours(-1),
                ExpiresOn         = Recording.UtcNow.AddHours(+1),
                IPRange           = new SasIPRange(IPAddress.None, IPAddress.None)
            };

            builder.SetPermissions(BlobContainerSasPermissions.All);
            return(builder.ToSasQueryParameters(userDelegationKey, accountName));
        }
Пример #16
0
        /// <inheritdoc/>
        public async Task <string> GetSasUrlAsync(Uri blobUri, TimeSpan ttl)
        {
            _ = blobUri ?? throw new ArgumentNullException(nameof(blobUri));

            try
            {
                var blobUriBuilder = new BlobUriBuilder(blobUri);

                // Create a SAS token that's valid for the TimeSpan, plus a back-off start for clock skew.
                BlobSasBuilder sasBuilder = new BlobSasBuilder
                {
                    BlobContainerName = blobUriBuilder.BlobContainerName,
                    BlobName          = blobUriBuilder.BlobName,
                    Resource          = "b", // "b" is for blob
                    StartsOn          = DateTimeOffset.UtcNow.AddMinutes(-5),
                    ExpiresOn         = DateTimeOffset.UtcNow + ttl,
                };

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

                var blobServiceClient = new BlobServiceClient(new UriBuilder(blobUriBuilder.Scheme, blobUriBuilder.Host).Uri, _tokenCredential, null);

                var userDelegation = (await blobServiceClient.GetUserDelegationKeyAsync(sasBuilder.StartsOn, sasBuilder.ExpiresOn).ConfigureAwait(false))?.Value;

                if (userDelegation == null)
                {
                    var msg = $@"Unable to get a user delegation key from the Storage service for blob {blobUri}";
                    _log.LogError(msg);
                    throw new Exception(msg);
                }

                var sasToken = sasBuilder.ToSasQueryParameters(userDelegation, blobUriBuilder.AccountName);
                blobUriBuilder.Sas = sasToken;

                // Construct the full URI, including the SAS token.
                return(blobUriBuilder.ToUri().ToString());
            }
            catch (RequestFailedException e)
            {
                var msg = $@"Unable to get a user delegation key from the Storage service for blob {blobUri}";
                _log.LogError(msg);
                throw new Exception(msg, e);
            }
            catch (Exception e)
            {
                var msg = $@"Failed to generate the SAS url for blob {blobUri}";
                _log.LogError(msg);
                throw new Exception(msg, e);
            }
        }
        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);
        }
        /// <summary>
        /// Create a container if doesn't exist, setting permission with policy, and return assosciated SAS signature
        /// </summary>
        /// <param name="account">Storage account</param>
        /// <param name="Key">Storage account key</param>
        /// <param name="blobUri">Blob endpoint URI</param>
        /// <param name="containerName">Name of the container to be created</param>
        /// <param name="policy">Name for the policy</param>
        /// <param name="start">Start time of the policy</param>
        /// <param name="end">Expire time of the policy</param>
        /// <param name="permissions">Blob access permissions</param>
        /// <returns>the SAS for the container, in full URI format.</returns>.
        private static async Task <string> CreateContainerWithPolicySASIfNotExistAsync(string account, string key, Uri blobUri, string containerName, string policy, DateTime start, DateTime end, string permissions)
        {
            // 1. form the credentail and initial client
            StagingStorageAccount      stagingCredentials  = new StagingStorageAccount(account, key, blobUri.ToString());
            StorageSharedKeyCredential shardKeyCredentials = new StorageSharedKeyCredential(account, key);
            BlobContainerClient        containerClient     = BlobUtilities.GetBlobContainerClient(containerName, stagingCredentials);

            // 2. create container if it doesn't exist
            containerClient.CreateIfNotExists();

            // 3. validate policy, create/overwrite if doesn't match
            BlobSignedIdentifier identifier = new BlobSignedIdentifier
            {
                Id           = policy,
                AccessPolicy = new BlobAccessPolicy
                {
                    Permissions = permissions,
                    StartsOn    = start,
                    ExpiresOn   = end,
                },
            };

            var  accessPolicy = (await containerClient.GetAccessPolicyAsync()).Value;
            bool policyFound  = accessPolicy.SignedIdentifiers.Any(i => i == identifier);

            if (policyFound == false)
            {
                await containerClient.SetAccessPolicyAsync(PublicAccessType.BlobContainer, permissions : new List <BlobSignedIdentifier> {
                    identifier
                });
            }

            BlobSasBuilder sasBuilder = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                StartsOn          = start,
                ExpiresOn         = end,
            };

            sasBuilder.SetPermissions(permissions);
            BlobUriBuilder builder = new BlobUriBuilder(containerClient.Uri)
            {
                Sas = sasBuilder.ToSasQueryParameters(shardKeyCredentials)
            };
            string fullSas = builder.ToString();

            return(fullSas);
        }
Пример #19
0
 public BlobSasQueryParameters GetNewBlobServiceSasCredentialsSnapshot(string containerName, string blobName, string snapshot, StorageSharedKeyCredential sharedKeyCredentials = default)
 {
     var builder = new BlobSasBuilder
     {
         BlobContainerName = containerName,
         BlobName = blobName,
         Snapshot = snapshot,
         Protocol = SasProtocol.None,
         StartsOn = Recording.UtcNow.AddHours(-1),
         ExpiresOn = Recording.UtcNow.AddHours(+1),
         IPRange = new SasIPRange(IPAddress.None, IPAddress.None),
         Version = ToSasVersion(_serviceVersion)
     };
     builder.SetPermissions(SnapshotSasPermissions.All);
     return builder.ToSasQueryParameters(sharedKeyCredentials ?? GetNewSharedKeyCredentials());
 }
Пример #20
0
        public string GenerateSasToken()
        {
            BlobSasBuilder builder = new BlobSasBuilder();

            builder.BlobContainerName = _storageServiceConfiguration.ContainerName;
            builder.ContentType       = "video/mp4";
            builder.SetPermissions(BlobAccountSasPermissions.Read);
            builder.StartsOn  = DateTimeOffset.UtcNow;
            builder.ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(90);
            var sasToken = builder
                           .ToSasQueryParameters(new StorageSharedKeyCredential(_storageServiceConfiguration.AccountName,
                                                                                _storageServiceConfiguration.Key))
                           .ToString();

            return(sasToken);
        }
Пример #21
0
        public string GenerateSASTokenForContainer(string containerName)
        {
            BlobSasBuilder builder = new BlobSasBuilder()
            {
                BlobContainerName = containerName,
                Resource          = "c", // "c" = container, "b" = blob
                StartsOn          = DateTimeOffset.UtcNow,
                ExpiresOn         = DateTimeOffset.UtcNow.AddHours(3)
            };

            builder.SetPermissions(BlobContainerSasPermissions.Read);

            var creds = new StorageSharedKeyCredential(options.AccountName, options.Key);

            return(builder.ToSasQueryParameters(creds).ToString());
        }
        public async Task SasBuilder()
        {
            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")));

                #region Snippet:SampleSnippetsBlobMigration_SasBuilder
                // Create BlobSasBuilder and specify parameters
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    // with no url in a client to read from, container and blob name must be provided if applicable
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    ExpiresOn         = DateTimeOffset.Now.AddHours(1)
                };
                // permissions applied separately, using the appropriate enum to the scope of your SAS
                sasBuilder.SetPermissions(BlobSasPermissions.Read);

                // 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();
                #endregion

                // successful download indicates pass
                await new BlobClient(sasUri).DownloadToAsync(new MemoryStream());
            }
            finally
            {
                await container.DeleteIfExistsAsync();
            }
        }
Пример #23
0
        public void GetAdHocBlobSasToken(string containerName, string blobName)
        {
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerName,
                BlobName          = blobName,
                Resource          = "b",//Value b is for generating token for a Blob and c is for container
                StartsOn          = DateTime.UtcNow.AddMinutes(-2),
                ExpiresOn         = DateTime.UtcNow.AddMinutes(10),
            };

            sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write); //multiple permissions can be added by using | symbol

            var sasToken = sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(GetKeyValueFromConnectionString("AccountName"), GetKeyValueFromConnectionString("AccountKey")));

            Console.WriteLine($"{new BlobClient(connectionString, containerName, blobName).Uri}?{sasToken}");
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");
            string  id          = req.Query["id"];
            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data        = JsonConvert.DeserializeObject(requestBody);

            id = id ?? data?.id;

            var response = await searchClient.GetDocumentAsync <SearchDocument>(id);


            object metadata_storage_path;

            response.Value.TryGetValue("metadata_storage_path", out metadata_storage_path);
            var storagePath = metadata_storage_path.ToString();
            var startIndex  = storagePath.IndexOf(Constants.containerName) + Constants.containerName.Length + 1;
            var blobName    = storagePath.Substring(startIndex);

            blobName = Uri.UnescapeDataString(blobName);
            log.LogInformation(blobName);

            var policy = new BlobSasBuilder
            {
                Protocol          = SasProtocol.HttpsAndHttp,
                BlobContainerName = storageContainerName,
                BlobName          = blobName,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow,
                ExpiresOn         = DateTimeOffset.UtcNow.AddHours(1),
                IPRange           = new SasIPRange(IPAddress.None, IPAddress.None)
            };

            policy.SetPermissions(BlobSasPermissions.Read);

            var sas = policy.ToSasQueryParameters(sharedStorageCredentials);

            LookupOutput output = new LookupOutput();

            output.document = response.Value;
            output.sasToken = sas.ToString();

            return(new OkObjectResult(output));
        }
        private async Task <string> GenerateSasUri(BlobItem blob, string tenant)
        {
            try
            {
                var storageAccount = await GetStorageAccount();

                var storageKey = await GetStorageKey();

                //  Defines the resource being accessed and for how long the access is allowed.
                var blobSasBuilder = new BlobSasBuilder
                {
                    StartsOn          = DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(15d)),
                    ExpiresOn         = DateTimeOffset.UtcNow.AddHours(1),
                    BlobContainerName = tenant,
                    Resource          = "b",
                    BlobName          = blob.Name,
                };

                //  Defines the type of permission.
                blobSasBuilder.SetPermissions(BlobSasPermissions.Read);

                //  Builds an instance of StorageSharedKeyCredential
                var storageSharedKeyCredential =
                    new StorageSharedKeyCredential(storageAccount.Credentials.AccountName, storageKey);

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


                // Construct the full URI, including the SAS token.
                var fullUri = new UriBuilder
                {
                    Scheme = "https",
                    Host   = $"{storageAccount.Credentials.AccountName}.blob.core.windows.net",
                    Path   = $"{tenant}/{blob.Name}",
                    Query  = sasQueryParameters.ToString()
                };
                return(fullUri.ToString());
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"An error occurred while generating the Sas Uri for blob {blob.Name}");
                throw;
            }
        }
Пример #26
0
        private async static Task <Uri> GetUserDelegationSasBlob(string containerName, string blobName)
        {
            // Construct the blob endpoint from the account name.
            string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", Settings.StorageAccount);


            var credential = new ClientSecretCredential(
                Settings.TenantId,
                Settings.ClientId,
                Settings.ClientSecret,
                new TokenCredentialOptions());

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

            // 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));

            // 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, Settings.StorageAccount).ToString();

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

            return(fullUri.Uri);
        }
Пример #27
0
        public static string GetWriteableSasUri(BlobContainerClient containerClient, StagingStorageAccount storageAccount)
        {
            var sasBuilder = new BlobSasBuilder
            {
                ExpiresOn         = DateTime.UtcNow.AddDays(1),
                BlobContainerName = containerClient.Name,
            };

            sasBuilder.SetPermissions(BlobSasPermissions.Write);
            StorageSharedKeyCredential credentials = GetSharedKeyCredential(storageAccount);
            BlobUriBuilder             builder     = new BlobUriBuilder(containerClient.Uri);

            builder.Sas = sasBuilder.ToSasQueryParameters(credentials);
            string fullSas = builder.ToString();

            return(fullSas);
        }
Пример #28
0
        public async Task <string> Url(string id)
        {
            var blob = _container.GetBlobClient(id);

            var sas = new BlobSasBuilder
            {
                BlobContainerName = blob.BlobContainerName,
                BlobName          = blob.Name,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow.AddMinutes(-15),
                ExpiresOn         = DateTimeOffset.UtcNow.AddMinutes(15)
            };

            sas.SetPermissions(BlobContainerSasPermissions.Read);

            return($"{blob.Uri}?{sas.ToSasQueryParameters(_key)}");
        }
Пример #29
0
        public string GetSasUri(BlobContainerClient container, string blobName)
        {
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = container.Name,
                BlobName          = blobName,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow.AddMinutes(-1),
                ExpiresOn         = DateTimeOffset.UtcNow.AddMinutes(2)
            };

            sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);

            string sasToken = sasBuilder.ToSasQueryParameters(Credential).ToString();

            return($"{container.Uri.AbsoluteUri}/{blobName}?{sasToken}");
        }
Пример #30
0
        public string GetContainerKey(string containerName, int permissions = 1, int expireDurationInHours = 12) //Default permission is read
        {
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerName,
                BlobName          = String.Empty,
                Resource          = "c",
                StartsOn          = DateTimeOffset.UtcNow,
                ExpiresOn         = DateTimeOffset.UtcNow.AddHours(expireDurationInHours)
            };

            sasBuilder.SetPermissions((BlobSasPermissions)permissions);
            var storageSharedKeyCredential = new StorageSharedKeyCredential(_storageAccountName,
                                                                            _storageAccountKey);
            string sasToken = sasBuilder.ToSasQueryParameters(storageSharedKeyCredential).ToString();

            return(sasToken);
        }