예제 #1
0
        internal string ToSasQuery(StorageSharedKeyCredential sasSigningCredentials, string containerName)
        {
            if (sasSigningCredentials is null)
            {
                throw new ArgumentNullException(nameof(sasSigningCredentials));
            }

            var sas = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                Protocol          = SasProtocol.Https,
                StartsOn          = StartTime,
                ExpiresOn         = ExpiryTime
            };

            sas.SetPermissions((BlobContainerSasPermissions)(int)Permissions);

            string query = sas.ToSasQueryParameters(sasSigningCredentials).ToString();

            return(query);
        }
예제 #2
0
        static void Main(string[] args)
        {
            string storageAccount = "az204testing";

            DateTimeOffset startTimeKey = DateTimeOffset.UtcNow;
            DateTimeOffset endTimeKey   = DateTimeOffset.UtcNow.AddDays(7);
            DateTimeOffset startTimeSAS = startTimeKey;
            DateTimeOffset endTimeSAS   = startTimeSAS.AddDays(1);

            Uri blobEndpointUri = new Uri($"https://{storageAccount}.blob.core.windows.net");

            var defaultCredentials = new DefaultAzureCredential(true);

            BlobServiceClient blobClient = new BlobServiceClient(blobEndpointUri,
                                                                 defaultCredentials);

            //Get the key. We are going to use this key for creating the SAS
            UserDelegationKey key = blobClient.GetUserDelegationKey(startTimeKey,
                                                                    endTimeKey);

            System.Console.WriteLine($"User Key Starts on: {key.SignedStartsOn}");
            System.Console.WriteLine($"User Key Expires on: {key.SignedExpiresOn}");
            System.Console.WriteLine($"User Key Service: {key.SignedService}");
            System.Console.WriteLine($"User Key Version: {key.SignedVersion}");

            //We need to use the BlobSasBuilder for creating the SAS
            BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
            {
                StartsOn  = startTimeSAS,
                ExpiresOn = endTimeSAS
            };

            //We set the permissions Create, List, Add, Read, and Write
            blobSasBuilder.SetPermissions("clarw");

            string sasToken = blobSasBuilder.ToSasQueryParameters
                                  (key, storageAccount).ToString();

            System.Console.WriteLine($"SAS Token: {sasToken}");
        }
예제 #3
0
        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_name;

            response.Value.TryGetValue("metadata_storage_name", out metadata_storage_name);

            var policy = new BlobSasBuilder
            {
                Protocol          = SasProtocol.HttpsAndHttp,
                BlobContainerName = storageContainerName,
                BlobName          = metadata_storage_name.ToString(),
                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));
        }
        public void AuthWithSasCredential()
        {
            //setup blob
            string containerName = Randomize("sample-container");
            string blobName      = Randomize("sample-file");
            var    container     = new BlobContainerClient(ConnectionString, containerName);

            try
            {
                container.Create();
                container.GetBlobClient(blobName).Upload(new MemoryStream(Encoding.UTF8.GetBytes("hello world")));

                // build SAS URI for sample
                BlobSasBuilder sas = new BlobSasBuilder
                {
                    ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
                };
                sas.SetPermissions(BlobSasPermissions.All);

                StorageSharedKeyCredential credential = new StorageSharedKeyCredential(StorageAccountName, StorageAccountKey);

                UriBuilder sasUri = new UriBuilder(this.StorageAccountBlobUri);
                sasUri.Path  = $"{containerName}/{blobName}";
                sasUri.Query = sas.ToSasQueryParameters(credential).ToString();

                string blobLocationWithSas = sasUri.Uri.ToString();

                #region Snippet:SampleSnippetsBlobMigration_SasUri
                BlobClient blob = new BlobClient(new Uri(blobLocationWithSas));
                #endregion

                var stream = new MemoryStream();
                blob.DownloadTo(stream);
                Assert.Greater(stream.Length, 0);
            }
            finally
            {
                container.Delete();
            }
        }
예제 #5
0
        /// <summary>
        /// This will return up to 3 s_tokens for the storage accounts
        /// </summary>
        /// <returns></returns>
        private void GetContainerSasUris()
        {
            // We need to refresh the s_tokens every time or they will become invalid.
            s_tokens = new string[3];
            s_containerAddresses = new string[3];

            string accountName = _configuration.GetSection("StorageAccountName")?.Value;
            string accountKey = _configuration.GetSection("StorageAccountKey")?.Value;
            StorageSharedKeyCredential storageSharedKeyCredential = new StorageSharedKeyCredential(accountName, accountKey);
            s_containerAddresses[0] = _configuration.GetSection("StorageContainerAddress")?.Value.ToLower();
            s_containerAddresses[1] = _configuration.GetSection("StorageContainerAddress2")?.Value.ToLower();
            s_containerAddresses[2] = _configuration.GetSection("StorageContainerAddress3")?.Value.ToLower();
            int s_containerAddressesLength = s_containerAddresses.Length;
            if (String.Equals(s_containerAddresses[1], defaultContainerUriValue))
            {
                s_containerAddressesLength--;
            }
            if (String.Equals(s_containerAddresses[2], defaultContainerUriValue))
            {
                s_containerAddressesLength--;
            }
            for (int i = 0; i < s_containerAddressesLength; i++) {
                BlobContainerClient container = new BlobContainerClient(new Uri(s_containerAddresses[i]), new StorageSharedKeyCredential(accountName, accountKey));
                var policy = new BlobSasBuilder
                {
                    Protocol = SasProtocol.HttpsAndHttp,
                    BlobContainerName = container.Name,
                    Resource = "c",
                    StartsOn = DateTimeOffset.UtcNow,
                    ExpiresOn = DateTimeOffset.UtcNow.AddHours(24),
                    IPRange = new SasIPRange(IPAddress.None, IPAddress.None)
                };
                policy.SetPermissions(BlobSasPermissions.Read);
                var sas = policy.ToSasQueryParameters(storageSharedKeyCredential);
                BlobUriBuilder  sasUri = new BlobUriBuilder(container.Uri);
                sasUri.Sas = sas;

                s_tokens[i] = "?" + sasUri.Sas.ToString();
            }
        }
예제 #6
0
        // </Snippet_ReadBlobWithSasAsync>

        #endregion

        #region

        // <Snippet_GetUserDelegationSasContainer>
        async static Task <Uri> GetUserDelegationSasContainer(BlobContainerClient blobContainerClient)
        {
            BlobServiceClient blobServiceClient = blobContainerClient.GetParentBlobServiceClient();

            // 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 userDelegationKey =
                await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
                                                                  DateTimeOffset.UtcNow.AddDays(7));

            // Create a SAS token that's valid for seven days.
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = blobContainerClient.Name,
                Resource          = "c",
                ExpiresOn         = DateTimeOffset.UtcNow.AddDays(7)
            };

            // Specify racwl permissions for the SAS.
            sasBuilder.SetPermissions(
                BlobContainerSasPermissions.Read |
                BlobContainerSasPermissions.Add |
                BlobContainerSasPermissions.Create |
                BlobContainerSasPermissions.Write |
                BlobContainerSasPermissions.List
                );

            // Add the SAS token to the container URI.
            BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobContainerClient.Uri)
            {
                // Specify the user delegation key.
                Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,
                                                      blobServiceClient.AccountName)
            };

            Console.WriteLine("Container user delegation SAS URI: {0}", blobUriBuilder);
            Console.WriteLine();
            return(blobUriBuilder.ToUri());
        }
예제 #7
0
        private async Task <string> GenerateSasUrl(string containerName, string blobName)
        {
            var storageAccount = Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT_NAME");

            // Create a BlobServiceClient that will authenticate through Active Directory
            Uri accountUri           = new Uri(String.Format("https://{0}.blob.core.windows.net/", storageAccount));
            BlobServiceClient client = new BlobServiceClient(accountUri, new DefaultAzureCredential());

            var containerClient = client.GetBlobContainerClient(containerName);

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

            UserDelegationKey key = await client.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow,
                                                                           DateTimeOffset.UtcNow.AddDays(7));

            string sasToken = sasBuilder.ToSasQueryParameters(key, storageAccount).ToString();

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

            return(fullUri.ToString());
        }
예제 #8
0
        /// <summary>
        /// Gets a URI that can be used to upload a specific blob to the blob container.
        /// </summary>
        /// <param name="containerName">Name of the container to upload the blob to.</param>
        /// <param name="blobName">Name of the blob.</param>
        /// <returns>Uri to the blob that includes the shared access key.</returns>
        public async Task <Uri> GetBlobUploadUrlAsync(string containerName, string blobName)
        {
            // Create container client using connection string and passed in container name.
            var containerClient = new BlobContainerClient(BlobConnectionString, containerName);

            // Create the container if it does not exist.
            await containerClient.CreateIfNotExistsAsync().ConfigureAwait(false);

            // Create a storage shared key to use to create a shared access signature.
            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(containerClient.AccountName, BlobAccountKey);

            // Create a blob client for the blob.
            BlobClient blobClient = containerClient.GetBlobClient(blobName);

            // Create a service level shared access signature that only allows uploading the blob to azure blob service.
            BlobSasBuilder sas = new BlobSasBuilder
            {
                BlobContainerName = containerName,
                BlobName          = blobName,
                ExpiresOn         = DateTime.UtcNow.AddMinutes(10),
            };

            // Allow read access
            sas.SetPermissions(BlobSasPermissions.Write);

            // 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", blobClient.AccountName),
                Path   = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0}/{1}", blobClient.BlobContainerName, blobClient.Name),
                Query  = sasToken,
            };

            return(fullUri.Uri);
        }
예제 #9
0
        public string GetUrlBlob(List <string> path)
        {
            if (!CheckPathParam(path))
            {
                _logger.LogError("Invalid path to create url blob {path}", path);
                throw new ArgumentException($"Invalid path for blob");
            }

            string blobName = string.Join("/", path);

            _logger.LogTrace("Creating url for blob {path}", blobName);

            var            blobClient = _client.GetBlobContainerClient(_containerName).GetBlobClient(blobName);
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                ExpiresOn = DateTime.UtcNow.AddDays(1),
            };

            sasBuilder.SetPermissions(BlobAccountSasPermissions.Read);

            return(blobClient.GenerateSasUri(sasBuilder).AbsoluteUri);
        }
예제 #10
0
        private string GetBlobSas(BlobClient blob)
        {
            // Create a user SAS that only allows reading for a minute
            BlobSasBuilder sas = new BlobSasBuilder
            {
                BlobContainerName = blob.BlobContainerName,
                BlobName          = blob.Name,
                Resource          = "b",
                ExpiresOn         = DateTimeOffset.UtcNow.AddDays(2)
            };

            // Allow read access
            sas.SetPermissions(BlobSasPermissions.Read);

            // Use the shared key to access the blob
            var storageSharedKeyCredential = new StorageSharedKeyCredential(
                config.GetValue <string>("StorageAccount:AccountName"),
                config.GetValue <string>("StorageAccount:AccountKey")
                );

            return('?' + sas.ToSasQueryParameters(storageSharedKeyCredential).ToString());
        }
        public async Task <string> GetAccessUrlWithSasTokenAsync(BlobBaseClient blob, string downloadName)
        {
            //const string policyName = "JOBLOG";
            var filename = WebUtility.UrlEncode(WebUtility.UrlDecode(downloadName));

            if (blob.CanGenerateSasUri)
            {
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName  = blob.BlobContainerName,
                    BlobName           = blob.Name,
                    Resource           = "b",
                    ContentDisposition = "attachment; filename=" + filename + ".log"
                };
                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                sasBuilder.StartsOn  = DateTimeOffset.UtcNow.AddHours(-1);
                sasBuilder.SetPermissions(BlobSasPermissions.Read);
                Uri sasUri = blob.GenerateSasUri(sasBuilder);
                return(await Task.FromResult(sasUri.OriginalString));
            }
            throw new Exception($"{blob.Name} cannot GenerateSasUri");
        }
예제 #12
0
        public async Task BlobVersionIdentitySas_AllPermissions()
        {
            // Arrange
            BlobServiceClient oauthService  = GetServiceClient_OauthAccount();
            string            containerName = GetNewContainerName();
            string            blobName      = GetNewBlobName();

            await using DisposingContainer test = await GetTestContainerAsync(containerName : containerName, service : oauthService);

            Response <UserDelegationKey> userDelegationKey = await oauthService.GetUserDelegationKeyAsync(
                startsOn : null,
                expiresOn : Recording.UtcNow.AddHours(1));

            AppendBlobClient           blob           = InstrumentClient(test.Container.GetAppendBlobClient(blobName));
            Response <BlobContentInfo> createResponse = await blob.CreateAsync();

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

            BlobSasBuilder blobSasBuilder = new BlobSasBuilder()
            {
                ExpiresOn         = Recording.UtcNow.AddDays(1),
                BlobContainerName = test.Container.Name,
                BlobName          = blobName,
                BlobVersionId     = createResponse.Value.VersionId
            };

            blobSasBuilder.SetPermissions(BlobVersionSasPermissions.All);

            BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blob.Uri)
            {
                VersionId = createResponse.Value.VersionId,
                Sas       = blobSasBuilder.ToSasQueryParameters(userDelegationKey.Value, oauthService.AccountName)
            };

            // Act
            AppendBlobClient sasBlobClient = InstrumentClient(new AppendBlobClient(blobUriBuilder.ToUri(), GetOptions()));
            await sasBlobClient.DeleteAsync();
        }
예제 #13
0
        public static Uri GetContainerSas(string containerName, StorageSharedKeyCredential key, BlobContainerSasPermissions permissions = BlobContainerSasPermissions.Read, uint durationMinutes = 10)
        {
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerName,
                Resource          = "c",
                StartsOn          = DateTimeOffset.UtcNow.AddMinutes(-5),
                ExpiresOn         = DateTimeOffset.UtcNow.AddMinutes(durationMinutes)
            };

            sasBuilder.SetPermissions(permissions);
            var sasToken = sasBuilder.ToSasQueryParameters(key).ToString();
            var fullUri  = new UriBuilder()
            {
                Scheme = "https",
                Host   = $"{key.AccountName}.blob.core.windows.net",
                Path   = $"{containerName}",
                Query  = sasToken
            };

            return(fullUri.Uri);
        }
예제 #14
0
        public async Task <Uri> GetBlobReadUri(string category, string blobName, long atLeast, long noLonger)
        {
            var containerClient = _serviceClient.GetBlobContainerClient(category);
            await containerClient.CreateIfNotExistsAsync();

            var blobClient = containerClient.GetBlobClient(blobName);

            if (blobClient != null && blobClient.CanGenerateSasUri)
            {
                return(blobClient.GenerateSasUri(BlobSasPermissions.Read, DateTimeOffset.UtcNow.AddSeconds(atLeast)));
            }

            // Try to compose a SAS token by getting a delegate key
            if (_delegationKey == null || _delegationKey.SignedExpiresOn < DateTime.UtcNow)
            {
                await UpdateDelegationKey();
            }

            // Create a new Sas uri & return it.
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = category,
                BlobName          = blobName,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow,
                ExpiresOn         = DateTimeOffset.UtcNow.AddSeconds(atLeast)
            };

            sasBuilder.SetPermissions(BlobSasPermissions.Read);
            var blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
            {
                // Specify the user delegation key.
                Sas = sasBuilder.ToSasQueryParameters(_delegationKey,
                                                      _serviceClient.AccountName)
            };

            return(blobUriBuilder.ToUri());
        }
예제 #15
0
        public async Task BlobSnapshotIdentitySas_AllPermissions()
        {
            // Arrange
            BlobServiceClient oauthService  = GetServiceClient_OauthAccount();
            string            containerName = GetNewContainerName();
            string            blobName      = GetNewBlobName();

            await using DisposingContainer test = await GetTestContainerAsync(containerName : containerName, service : oauthService);

            Response <UserDelegationKey> userDelegationKey = await oauthService.GetUserDelegationKeyAsync(
                startsOn : null,
                expiresOn : Recording.UtcNow.AddHours(1));

            AppendBlobClient blob = InstrumentClient(test.Container.GetAppendBlobClient(blobName));
            await blob.CreateAsync();

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

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

            blobSasBuilder.SetPermissions(SnapshotSasPermissions.All);

            BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blob.Uri)
            {
                Snapshot = snapshotResponse.Value.Snapshot,
                Sas      = blobSasBuilder.ToSasQueryParameters(userDelegationKey.Value, oauthService.AccountName)
            };

            // Act
            AppendBlobClient sasBlobClient = InstrumentClient(new AppendBlobClient(blobUriBuilder.ToUri(), GetOptions()));
            await sasBlobClient.GetPropertiesAsync();
        }
예제 #16
0
        private static Uri GetServiceSasUriForBlob(ILogger log, BlobClient blobClient,
                                                   string containerName, string blobName,
                                                   string storedPolicyName = null)
        {
            // Check whether this BlobClient object has been authorized with Shared Key.
            log.LogInformation($"trying to get sas blobClient==null?{blobClient==null}. ");

            if (blobClient != null && blobClient.CanGenerateSasUri)
            {
                // Create a SAS token that's valid for one hour.
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = containerName,
                    BlobName          = blobName,
                    Resource          = "b"
                };

                if (storedPolicyName == null)
                {
                    sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                    sasBuilder.SetPermissions(BlobSasPermissions.Read |
                                              BlobSasPermissions.Write);
                }
                else
                {
                    sasBuilder.Identifier = storedPolicyName;
                }

                Uri sasUri = blobClient.GenerateSasUri(sasBuilder);

                return(sasUri);
            }
            else
            {
                log.LogError("BlobClient must be authorized with Shared Key credentials to create a service SAS.");
                return(null);
            }
        }
예제 #17
0
        // </Snippet_GetServiceSasUriForDirectory>

        #endregion


        #region GetServiceSasUriForBlob

        //-------------------------------------------------
        // Get service SAS for blob
        //-------------------------------------------------

        // <Snippet_GetServiceSasUriForBlob>
        private static Uri GetServiceSasUriForBlob(BlobClient blobClient,
                                                   string storedPolicyName = null)
        {
            // Check whether this BlobClient object has been authorized with Shared Key.
            if (blobClient.CanGenerateSasUri)
            {
                // Create a SAS token that's valid for one hour.
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
                    BlobName          = blobClient.Name,
                    Resource          = "b"
                };

                if (storedPolicyName == null)
                {
                    sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                    sasBuilder.SetPermissions(BlobSasPermissions.Read |
                                              BlobSasPermissions.Write);
                }
                else
                {
                    sasBuilder.Identifier = storedPolicyName;
                }

                Uri sasUri = blobClient.GenerateSasUri(sasBuilder);
                Console.WriteLine("SAS URI for blob is: {0}", sasUri);
                Console.WriteLine();

                return(sasUri);
            }
            else
            {
                Console.WriteLine(@"BlobClient must be authorized with Shared Key 
                                  credentials to create a service SAS.");
                return(null);
            }
        }
예제 #18
0
        private BlobSasBuilder BuildBlobSasBuilder(bool includeBlob, bool includeSnapshot, string containerName, string blobName, TestConstants constants)
        {
            var builder = new BlobSasBuilder
            {
                Version            = null,
                Protocol           = constants.Sas.Protocol,
                StartsOn           = constants.Sas.StartTime,
                ExpiresOn          = constants.Sas.ExpiryTime,
                IPRange            = constants.Sas.IPRange,
                Identifier         = constants.Sas.Identifier,
                BlobContainerName  = containerName,
                BlobName           = includeBlob ? blobName : null,
                Snapshot           = includeSnapshot ? Snapshot : null,
                CacheControl       = constants.Sas.CacheControl,
                ContentDisposition = constants.Sas.ContentDisposition,
                ContentEncoding    = constants.Sas.ContentEncoding,
                ContentLanguage    = constants.Sas.ContentLanguage,
                ContentType        = constants.Sas.ContentType
            };

            builder.SetPermissions(BlobAccountSasPermissions.Read | BlobAccountSasPermissions.Write | BlobAccountSasPermissions.Delete);
            return(builder);
        }
예제 #19
0
        public void GetAccessPolicyBasedContainerSasToken(string containerName, string accessPolicy)
        {
            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerName,
                Resource          = "c", //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(BlobContainerSasPermissions.Read | BlobContainerSasPermissions.Write | BlobContainerSasPermissions.List); //multiple permissions can be added by using | symbol

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


            //Console.WriteLine($"{new BlobContainerClient(connectionString, containerName).Uri}?{sasToken}");
            Console.WriteLine($"{new BlobContainerClient(connectionString, containerName).Uri}?{sasToken}&restype=container&comp=list");

            /* Note : If you want to list the items inside container and view those details in a browser based on the generated SAS token
             * then two additional query parameters has to be appended to the token
             * the Query parameters are "restype=container&comp=list"
             */
        }
        public async Task BlobSasBuilder_PreauthorizedAgentObjectId()
        {
            // Arrange
            BlobServiceClient oauthService           = GetServiceClient_OauthAccount();
            string            containerName          = GetNewContainerName();
            string            preauthorizedAgentGuid = Recording.Random.NewGuid().ToString();

            await using DisposingContainer test = await GetTestContainerAsync(service : oauthService, containerName : containerName);

            // Arrange
            Response <UserDelegationKey> userDelegationKey = await oauthService.GetUserDelegationKeyAsync(
                startsOn : null,
                expiresOn : Recording.UtcNow.AddHours(1));

            BlobSasBuilder BlobSasBuilder = new BlobSasBuilder
            {
                StartsOn                   = Recording.UtcNow.AddHours(-1),
                ExpiresOn                  = Recording.UtcNow.AddHours(1),
                BlobContainerName          = containerName,
                PreauthorizedAgentObjectId = preauthorizedAgentGuid
            };

            BlobSasBuilder.SetPermissions(BlobSasPermissions.All);

            BlobUriBuilder BlobUriBuilder = new BlobUriBuilder(test.Container.Uri)
            {
                Sas = BlobSasBuilder.ToSasQueryParameters(userDelegationKey, test.Container.AccountName)
            };

            BlobContainerClient containerClient = InstrumentClient(new BlobContainerClient(BlobUriBuilder.ToUri(), GetOptions()));

            // Act
            BlobClient blobClient = containerClient.GetBlobClient(GetNewBlobName());
            await blobClient.UploadAsync(new MemoryStream());

            await blobClient.ExistsAsync();
        }
예제 #21
0
        public async Task <string> GetBlobSasToken(string url, string userAssignedClientId)
        {
            var uri        = new Uri(url);
            var credential = new DefaultAzureCredential(new DefaultAzureCredentialOptions {
                ManagedIdentityClientId = userAssignedClientId
            });
            var blobClient  = new BlobServiceClient(new Uri($"https://{uri.Host}"), credential);
            var accountName = blobClient.AccountName;

            Console.WriteLine(uri.Segments[1].Trim('/'));

            var delegationKey = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7));

            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = uri.Segments[1].Trim('/'),
                BlobName          = uri.Segments[2],
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow,
                ExpiresOn         = DateTimeOffset.UtcNow.AddHours(1)
            };

            sasBuilder.SetPermissions(BlobSasPermissions.Read);
            Console.WriteLine(sasBuilder.Permissions);
            var sasQueryParams = sasBuilder.ToSasQueryParameters(delegationKey, accountName).ToString();

            UriBuilder sasUri = new UriBuilder()
            {
                Scheme = "https",
                Host   = uri.Host,
                Path   = uri.AbsolutePath,
                Query  = sasQueryParams
            };

            return(sasUri.ToString());
        }
예제 #22
0
        /// <summary>
        /// Creates a public link to access a file that expires in 1 hour.
        /// </summary>
        /// <param name="destination"></param>
        /// <returns></returns>
        /// <seealso cref="https://www.nuget.org/packages/Azure.Storage.Blobs"/>
        /// <seealso cref="https://docs.microsoft.com/pt-br/azure/storage/blobs/storage-quickstart-blobs-dotnet#configure-your-storage-connection-string"/>
        /// <seealso cref="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/storage"/>
        public async Task <string> CreateSharedUrl(FilePath destination)
        {
            // Create a SharedKeyCredential that we can use to sign the SAS token
            var accountName = GetAccountNameFromConnectionString();
            var accountKey  = GetAccountKeyFromConnectionString();
            StorageSharedKeyCredential credential = new StorageSharedKeyCredential(accountName, accountKey);

            // Create a SAS token that's valid for one hour.
            // Be careful with SAS start time. If you set the start time for a SAS to now, then due to clock skew (differences in current time according to different machines), failures may be observed intermittently for the first few minutes. In general, set the start time to be at least 15 minutes in the past. Or, don't set it at all, which will make it valid immediately in all cases. The same generally applies to expiry time as well--remember that you may observe up to 15 minutes of clock skew in either direction on any request. For clients using a REST version prior to 2012-02-12, the maximum duration for a SAS that does not reference a stored access policy is 1 hour, and any policies specifying longer term than that will fail.
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = destination.Folder,
                BlobName          = destination.Path,
                Resource          = "b",
                //StartsOn = DateTimeOffset.UtcNow.AddMinutes(-15),
                ExpiresOn = DateTimeOffset.UtcNow.AddHours(1)
            };

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

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

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

            return(await Task.FromResult(fullUri.Uri.ToString()));
        }
        public async Task BlobSasBuilder_CorrelationId()
        {
            // Arrange
            BlobServiceClient oauthService  = GetServiceClient_OauthAccount();
            string            containerName = GetNewContainerName();

            await using DisposingContainer test = await GetTestContainerAsync(service : oauthService, containerName : containerName);

            // Arrange
            Response <UserDelegationKey> userDelegationKey = await oauthService.GetUserDelegationKeyAsync(
                startsOn : null,
                expiresOn : Recording.UtcNow.AddHours(1));

            BlobSasBuilder blobSasBuilder = new BlobSasBuilder
            {
                StartsOn          = Recording.UtcNow.AddHours(-1),
                ExpiresOn         = Recording.UtcNow.AddHours(1),
                BlobContainerName = containerName,
                CorrelationId     = Recording.Random.NewGuid().ToString()
            };

            blobSasBuilder.SetPermissions(BlobSasPermissions.All);

            BlobUriBuilder blobUriBuilder = new BlobUriBuilder(test.Container.Uri)
            {
                Sas = blobSasBuilder.ToSasQueryParameters(userDelegationKey, test.Container.AccountName)
            };

            BlobContainerClient containerClient = InstrumentClient(new BlobContainerClient(blobUriBuilder.ToUri(), GetOptions()));

            // Act
            await foreach (BlobItem pathItem in containerClient.GetBlobsAsync())
            {
                // Just make sure the call succeeds.
            }
        }
예제 #24
0
        static async Task Main(string[] args)
        {
            string connectionString = "CONNECTION_STRING";
            string containerName    = "fileuploadsample";
            string blobFileName     = "sample.png";
            // Upload file to blob
            BlobContainerClient containerClient = new BlobContainerClient(connectionString, containerName);
            await containerClient.CreateIfNotExistsAsync(PublicAccessType.None); //Making blob private.

            BlobClient blobClient = new BlobClient(connectionString, containerName, blobFileName);

            using FileStream fileStream = File.OpenRead(blobFileName);
            await blobClient.UploadAsync(fileStream, true);

            fileStream.Close();

            Console.WriteLine(blobClient.Uri.ToString());

            // Generate SAS URI for blob
            BlobSasBuilder sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerClient.Name,
                Resource          = "b",
                BlobName          = blobClient.Name
            };

            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
            sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);

            if (blobClient.CanGenerateSasUri)
            {
                Uri blobSasUri = blobClient.GenerateSasUri(sasBuilder);
                Console.WriteLine(blobSasUri.ToString());
            }
            Console.ReadLine();
        }
예제 #25
0
        private string GetAzureContainerSASToken()
        {
            // Check whether this BlobContainerClient object has been authorized with Shared Key.
            if (azureContainerClient.CanGenerateSasUri)
            {
                // Create a SAS token that's valid for one hour.
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = azureContainerClient.Name,
                    Resource          = "c"
                };

                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                sasBuilder.SetPermissions(permissions: BlobAccountSasPermissions.Read | BlobAccountSasPermissions.Create);

                return(sasBuilder.ToSasQueryParameters(new StorageSharedKeyCredential(azureContainerClient.AccountName, azureAccountKey)).ToString());
            }
            else
            {
                Console.WriteLine(@"BlobContainerClient must be authorized with Shared Key 
                          credentials to create a service SAS.");
                return(null);
            }
        }
예제 #26
0
        public string Getpath(string fileName)
        {
            if (fileName != null)
            {
                var imagesAccesKey             = _configuration.GetConnectionString("ImagesAccessKey");
                var storageName                = _configuration.GetConnectionString("StorageName");
                StorageSharedKeyCredential key = new StorageSharedKeyCredential(storageName, imagesAccesKey);
                var            container       = GetContainer();
                var            blob            = container.GetBlobClient(fileName);
                BlobSasBuilder sasBuilder      = new BlobSasBuilder()
                {
                    BlobContainerName = container.Name,
                    BlobName          = blob.Name,
                    Resource          = "b",
                };
                sasBuilder.StartsOn  = DateTimeOffset.UtcNow;
                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(1);
                sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);
                string sasToken = sasBuilder.ToSasQueryParameters(key).ToString();
                return($"{container.GetBlockBlobClient(blob.Name).Uri}?{sasToken}");
            }

            return(fileName);
        }
예제 #27
0
        public async Task <Result <string> > UploadProducerDeliveryBatchAsync(Guid producerId, Guid deliveryBatchId, string filenameWithExtension, byte[] data, CancellationToken token)
        {
            var containerClient =
                new BlobContainerClient(_storageOptions.ConnectionString, _storageOptions.Containers.DeliveryBatches);
            await containerClient.CreateIfNotExistsAsync(cancellationToken : token);

            var blobClient = containerClient.GetBlobClient($"users/{producerId:N}/{deliveryBatchId:N}/{SanitizeFileName(filenameWithExtension)}");
            await blobClient.DeleteIfExistsAsync(cancellationToken : token);

            using (var ms = new MemoryStream(data))
                await blobClient.UploadAsync(ms, token);

            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = _storageOptions.Containers.DeliveryBatches,
                BlobName          = blobClient.Name,
                Resource          = "b",
                StartsOn          = DateTimeOffset.UtcNow.AddHours(-1),
                ExpiresOn         = DateTimeOffset.UtcNow.AddYears(10)
            };

            sasBuilder.SetPermissions(BlobSasPermissions.Read);
            return(Success <string>(GetBlobSasUri(blobClient, sasBuilder, _storageOptions.Containers.DeliveryBatches)));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("Storage function processed a request.");

            string filename            = req.Headers["Filename"];
            string validity            = req.Headers["Validity"];
            var    contentType         = req.ContentType;
            var    overrideContentType = req.Headers["X-Content-Type"];

            if (!string.IsNullOrEmpty(overrideContentType))
            {
                contentType = overrideContentType;
            }

            if (string.IsNullOrEmpty(contentType))
            {
                log.LogWarning("Content-Type is required header.");
                return(new BadRequestObjectResult("Content-Type is required header."));
            }

            if (!req.ContentLength.HasValue)
            {
                log.LogWarning("Content-Length is required header.");
                return(new BadRequestObjectResult("Content-Length is required header."));
            }

            var duration = Convert.ToInt32(validity);

            const string containerName           = "files";
            var          storageConnectionString = Environment.GetEnvironmentVariable("Storage");
            var          storageAccount          = CloudStorageAccount.Parse(storageConnectionString);
            var          accountName             = storageAccount.Credentials.AccountName;
            var          KeyValue            = storageAccount.Credentials.ExportBase64EncodedKey();
            var          blobServiceClient   = new BlobServiceClient(storageConnectionString);
            var          blobContainerClient = blobServiceClient.GetBlobContainerClient(containerName);

            await blobContainerClient.CreateIfNotExistsAsync(PublicAccessType.None);

            var blobClient = blobContainerClient.GetBlobClient(filename);
            await blobClient.UploadAsync(req.Body, new BlobUploadOptions()
            {
                HttpHeaders = new BlobHttpHeaders()
                {
                    ContentType = contentType
                }
            });

            var sasBuilder = new BlobSasBuilder()
            {
                BlobContainerName = containerName,
                BlobName          = filename,
                Resource          = "b", // b=blob
                ExpiresOn         = DateTimeOffset.UtcNow.AddSeconds(duration)
            };

            sasBuilder.SetPermissions(BlobSasPermissions.Read);
            var credentials     = new StorageSharedKeyCredential(accountName, KeyValue);
            var queryParameters = sasBuilder.ToSasQueryParameters(credentials);

            return(new OkObjectResult(new FileResponse()
            {
                Uri = $"{blobClient.Uri}?{queryParameters}",
                ExpiresOn = sasBuilder.ExpiresOn
            }));
        }
        public static async Task RunAsync([EventGridTrigger] EventGridEvent eventGridEvent, ILogger log)
        {
            //Extracting content type and url of the blob triggering the function
            var jsondata = JsonConvert.SerializeObject(eventGridEvent.Data);
            var tmp      = new { contentType = "", url = "" };
            var data     = JsonConvert.DeserializeAnonymousType(jsondata, tmp);

            //Checking if the trigger was iniatiated for a PDF File.
            if (data.contentType == "application/pdf")
            {
                var pdfUrl = data.url;

                string endpoint = System.Environment.GetEnvironmentVariable("FormsRecognizerEndpoint", EnvironmentVariableTarget.Process);
                string apiKey   = System.Environment.GetEnvironmentVariable("FormsRecognizerKey", EnvironmentVariableTarget.Process);
                string contosoStorageConnectionString = System.Environment.GetEnvironmentVariable("ContosoStorageConnectionString", EnvironmentVariableTarget.Process);
                string cosmosEndpointUrl = System.Environment.GetEnvironmentVariable("CosmosDBEndpointUrl", EnvironmentVariableTarget.Process);
                string cosmosPrimaryKey  = System.Environment.GetEnvironmentVariable("CosmosDBPrimaryKey", EnvironmentVariableTarget.Process);

                //Create a SAS Link to give Forms Recognizer read access to the document
                BlobServiceClient   blobServiceClient = new BlobServiceClient(contosoStorageConnectionString);
                BlobContainerClient container         = new BlobContainerClient(contosoStorageConnectionString, "claims");
                string         blobName   = pdfUrl.Split('/').Last();
                BlobClient     blob       = container.GetBlobClient(blobName);
                BlobSasBuilder sasBuilder = new BlobSasBuilder()
                {
                    BlobContainerName = blob.GetParentBlobContainerClient().Name,
                    BlobName          = blob.Name,
                    Resource          = "b"
                };
                sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                sasBuilder.SetPermissions(BlobSasPermissions.Read);
                Uri sasUri = blob.GenerateSasUri(sasBuilder);

                var credential = new AzureKeyCredential(apiKey);

                //Get the latest trained model
                var formTrainingClient = new FormTrainingClient(new Uri(endpoint), credential);
                Pageable <CustomFormModelInfo> formsModels = formTrainingClient.GetCustomModels();
                var latestModel = (from inc in formsModels orderby inc.TrainingCompletedOn descending select inc).FirstOrDefault();

                //TODO:Run the document through the model

                //Insert documents into CosmosDB
                var cosmosClient    = new CosmosClient(cosmosEndpointUrl, cosmosPrimaryKey);
                var cosmosDatabase  = (await cosmosClient.CreateDatabaseIfNotExistsAsync("Contoso")).Database;
                var cosmosContainer = (await cosmosDatabase.CreateContainerIfNotExistsAsync("Claims", "/InsuredID")).Container;

                Model.ClaimsDocument processedDocument = new Model.ClaimsDocument();
                processedDocument.DocumentDate = new DateTime(int.Parse(blobName.Substring(0, 4)),
                                                              int.Parse(blobName.Substring(4, 2)), int.Parse(blobName.Substring(6, 2)));
                processedDocument.PatientName = forms[0].Fields["PatientName"].ValueData?.Text;
                processedDocument.InsuredID   = forms[0].Fields["InsuredID"].ValueData?.Text;
                processedDocument.Diagnosis   = forms[0].Fields["Diagnosis"].ValueData?.Text;
                decimal.TryParse(forms[0].Fields["TotalCharges"].ValueData?.Text, out decimal totalCharges);
                processedDocument.TotalCharges = totalCharges;
                DateTime.TryParse(forms[0].Fields["PatientBirthDate"].ValueData?.Text, out DateTime patientBirthDate);
                processedDocument.PatientBirthDate = patientBirthDate;
                decimal.TryParse(forms[0].Fields["AmountPaid"].ValueData?.Text, out decimal amountPaid);
                processedDocument.AmountPaid = amountPaid;
                decimal.TryParse(forms[0].Fields["AmountDue"].ValueData?.Text, out decimal amountDue);
                processedDocument.AmountDue = amountDue;
                processedDocument.FileName  = blobName;
                if (processedDocument.InsuredID == null)
                {
                    processedDocument.Id = Guid.NewGuid().ToString();
                }
                else
                {
                    processedDocument.Id = processedDocument.InsuredID;
                }

                try
                {
                    ItemResponse <Model.ClaimsDocument> cosmosResponse = await
                                                                         cosmosContainer.CreateItemAsync(processedDocument, new PartitionKey(processedDocument.InsuredID));
                }
                catch (CosmosException ex) when(ex.StatusCode == System.Net.HttpStatusCode.Conflict)
                {
                    //Conflicting EnsurerID is silently ignored for demo purposes.
                }
            }
            log.LogInformation(eventGridEvent.Data.ToString());
        }
        private async Task CreateTicketImageAsync(int ticketId)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                throw new PlatformNotSupportedException("Ticket rendering must run on Windows environment");
            }

            var ticketImageBlob = new MemoryStream();

            using var connection = new SqlConnection(_configuration.GetValue <string>("App:SqlDatabase:ConnectionString"));

            // Retrieve the ticket from the database.
            _logger.LogInformation($"Retrieving details for ticket \"{ticketId}\" from SQL Database...");
            await connection.OpenAsync();

            var getTicketCommand = connection.CreateCommand();

            getTicketCommand.CommandText = "SELECT Concerts.Artist, Concerts.Location, Concerts.StartTime, Concerts.Price, Users.DisplayName FROM Tickets INNER JOIN Concerts ON Tickets.ConcertId = Concerts.Id INNER JOIN Users ON Tickets.UserId = Users.Id WHERE Tickets.Id = @id";
            getTicketCommand.Parameters.Add(new SqlParameter("id", ticketId));
            using (var ticketDataReader = await getTicketCommand.ExecuteReaderAsync())
            {
                // Get ticket details.
                var hasRows = await ticketDataReader.ReadAsync();

                if (hasRows == false)
                {
                    _logger.LogWarning($"No Ticket found for id:{ticketId}");
                    return; //this ticket was not found
                }

                var artist    = ticketDataReader.GetString(0);
                var location  = ticketDataReader.GetString(1);
                var startTime = ticketDataReader.GetDateTimeOffset(2);
                var price     = ticketDataReader.GetDouble(3);
                var userName  = ticketDataReader.GetString(4);

                // Generate the ticket image.
                using (var headerFont = new Font("Arial", 18, FontStyle.Bold))
                    using (var textFont = new Font("Arial", 12, FontStyle.Regular))
                        using (var bitmap = new Bitmap(640, 200, PixelFormat.Format24bppRgb))
                            using (var graphics = Graphics.FromImage(bitmap))
                            {
                                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                                graphics.Clear(Color.White);

                                // Print concert details.
                                graphics.DrawString(artist, headerFont, Brushes.DarkSlateBlue, new PointF(10, 10));
                                graphics.DrawString($"{location}   |   {startTime.UtcDateTime}", textFont, Brushes.Gray, new PointF(10, 40));
                                graphics.DrawString($"{userName}   |   {price.ToString("c")}", textFont, Brushes.Gray, new PointF(10, 60));

                                // Print a fake barcode.
                                var random = new Random();
                                var offset = 15;
                                while (offset < 620)
                                {
                                    var width = 2 * random.Next(1, 3);
                                    graphics.FillRectangle(Brushes.Black, offset, 90, width, 90);
                                    offset += width + (2 * random.Next(1, 3));
                                }

                                // Save to blob storage.
                                _logger.LogInformation("Uploading image to blob storage...");
                                bitmap.Save(ticketImageBlob, ImageFormat.Png);
                            }
            }
            ticketImageBlob.Position = 0;
            _logger.LogInformation("Successfully generated image.");

            var storageAccountConnStr = _configuration.GetValue <string>("App:StorageAccount:ConnectionString");
            var blobServiceClient     = new BlobServiceClient(storageAccountConnStr);

            //  Gets a reference to the container.
            var blobContainerClient = blobServiceClient.GetBlobContainerClient("tickets");

            //  Gets a reference to the blob in the container
            var blobClient = blobContainerClient.GetBlobClient($"ticket-{ticketId}.png");
            var blobInfo   = await blobClient.UploadAsync(ticketImageBlob, overwrite : true);

            _logger.LogInformation("Successfully wrote blob to storage.");

            // Update the ticket in the database with the image URL.
            // Creates a client to the BlobService using the connection string.

            //  Defines the resource being accessed and for how long the access is allowed.
            var blobSasBuilder = new BlobSasBuilder
            {
                StartsOn  = DateTime.UtcNow.AddMinutes(-5),
                ExpiresOn = DateTime.UtcNow.Add(TimeSpan.FromDays(30)),
            };

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

            //  Builds the Sas URI.
            var queryUri = blobClient.GenerateSasUri(blobSasBuilder);

            _logger.LogInformation($"Updating ticket with image URL {queryUri}...");
            var updateTicketCommand = connection.CreateCommand();

            updateTicketCommand.CommandText = "UPDATE Tickets SET ImageUrl=@imageUrl WHERE Id=@id";
            updateTicketCommand.Parameters.Add(new SqlParameter("id", ticketId));
            updateTicketCommand.Parameters.Add(new SqlParameter("imageUrl", queryUri.ToString()));
            await updateTicketCommand.ExecuteNonQueryAsync();

            _logger.LogInformation("Successfully updated database with SAS.");
        }