Ejemplo n.º 1
0
        public async Task <string> GetBlobSAPUrlFromBlobPathAsync(CloudStorageAccount storageAccount, string containerName, string blobPath, string sharedAccessPolicyName)
        {
            string result = string.Empty;

            if (storageAccount == null || string.IsNullOrWhiteSpace(containerName) || string.IsNullOrWhiteSpace(blobPath) || string.IsNullOrWhiteSpace(sharedAccessPolicyName))
            {
                return(result);
            }

            CloudBlob blob = await this.GetBlobFromPathAsync(storageAccount, containerName, blobPath);

            CloudBlobContainer container = await this.GetContainerAsync(storageAccount, containerName, true);

            SharedAccessBlobPolicy policy = await this.GetSharedAccessPolicy(container, sharedAccessPolicyName);

            if (policy != null)
            {
                result = blob.Uri.AbsoluteUri + blob.GetSharedAccessSignature(policy);
            }

            return(result);
        }
Ejemplo n.º 2
0
        public override async Task <FileData> GetAsync(FileGetOptions fileGetOptions)
        {
            FileData file = new FileData();

            CloudStorageAccount storageAccount = Authorized(fileGetOptions);

            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            CloudBlobContainer container = blobClient.GetContainerReference(fileGetOptions.Folder.ToLower());

            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileGetOptions.Key);

            switch (fileGetOptions.FileTransfer)
            {
            case Enum.FileTransferOptions.Stream:
                await blockBlob.DownloadToStreamAsync(file.Stream);

                break;

            case Enum.FileTransferOptions.Url:
                file.Loc = blockBlob.Uri.AbsoluteUri;
                break;

            case Enum.FileTransferOptions.SecureUrl:

                var policy = new SharedAccessBlobPolicy()
                {
                    Permissions            = SharedAccessBlobPermissions.Read,
                    SharedAccessExpiryTime = DateTime.UtcNow + fileGetOptions.SecureLinkTimeToLive
                };

                file.Loc = (blockBlob.Uri.AbsoluteUri + blockBlob.GetSharedAccessSignature(policy));
                break;
            }

            file.Type = "Mircosoft Azure Blob Storage";

            return(file);
        }
Ejemplo n.º 3
0
        static public string GenerateSasUri(string blobStorageEndpointFormat, string storageAccount, string storageAccountKey,
                                            string blobContainer, string vhdName, int hours = 10, bool read = true, bool write = true, bool delete = true, bool list = true)
        {
            string destinationSasUri = string.Format(@blobStorageEndpointFormat, storageAccount) + string.Format("/{0}/{1}", blobContainer, vhdName);
            var    destinationBlob   = new CloudPageBlob(new Uri(destinationSasUri), new StorageCredentials(storageAccount, storageAccountKey));
            SharedAccessBlobPermissions permission = 0;

            permission |= (read) ? SharedAccessBlobPermissions.Read : 0;
            permission |= (write) ? SharedAccessBlobPermissions.Write : 0;
            permission |= (delete) ? SharedAccessBlobPermissions.Delete : 0;
            permission |= (list) ? SharedAccessBlobPermissions.List : 0;

            var policy = new SharedAccessBlobPolicy()
            {
                Permissions            = permission,
                SharedAccessExpiryTime = DateTime.UtcNow + TimeSpan.FromHours(hours)
            };

            string destinationBlobToken = destinationBlob.GetSharedAccessSignature(policy);

            return(destinationSasUri + destinationBlobToken);
        }
Ejemplo n.º 4
0
        public static string GetBlobWriteTokenUri(CloudBlobContainer container, string blobRef)
        {
            blobRef = blobRef.Replace("/", "");

            //Get a reference to a blob within the container.
            CloudBlockBlob blob = container.GetBlockBlobReference(blobRef);

            //Set the expiry time and permissions for the blob.
            //In this case the start time is specified as a few minutes in the past, to mitigate clock skew.
            //The shared access signature will be valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();

            sasConstraints.SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5);
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24);
            sasConstraints.Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write;

            //Generate the shared access signature on the blob, setting the constraints directly on the signature.
            string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            return(string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sasBlobToken));
        }
Ejemplo n.º 5
0
        internal string SetAzureContainerStoredAccessPolicy(IStorageBlobManagement localChannel, string containerName, string policyName, DateTime?startTime, DateTime?expiryTime, string permission, bool noStartTime, bool noExpiryTime)
        {
            //Get existing permissions
            CloudBlobContainer       container = localChannel.GetContainerReference(containerName);
            BlobContainerPermissions blobContainerPermissions = localChannel.GetContainerPermissions(container, null, null, OperationContext);

            //Set the policy with new value
            if (!blobContainerPermissions.SharedAccessPolicies.Keys.Contains(policyName))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.PolicyNotFound, policyName));
            }

            SharedAccessBlobPolicy policy = blobContainerPermissions.SharedAccessPolicies[policyName];

            AccessPolicyHelper.SetupAccessPolicy <SharedAccessBlobPolicy>(policy, startTime, expiryTime, permission, noStartTime, noExpiryTime);
            blobContainerPermissions.SharedAccessPolicies[policyName] = policy;

            //Set permission back to container
            localChannel.SetContainerPermissions(container, blobContainerPermissions, null, null, OperationContext);
            WriteObject(AccessPolicyHelper.ConstructPolicyOutputPSObject <SharedAccessBlobPolicy>(blobContainerPermissions.SharedAccessPolicies, policyName));
            return(policyName);
        }
Ejemplo n.º 6
0
        public static async Task <GetBlobSasTokenResponse> GetBlobSasTokens(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest request,
            ILogger log)
        {
            // Expecting a JSON array of filenames in the request.
            // Going to generate and return individual tokens for each file.
            var fileNames = await GetFileNamesFromRequest(request);

            var storageAccount = CloudStorageAccount.Parse(Environment.GetEnvironmentVariable(ConnectionStringVariableName));
            var container      = storageAccount.CreateCloudBlobClient().GetContainerReference(ContainerName);

            // Just to ensure the container exists
            await container.CreateIfNotExistsAsync();

            var policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(TokenTtlInMinutes),
                Permissions            = SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Write,
            };

            // userId will be used as a folder name. Generated tokens will be tied to that folder.
            string userId = await Helpers.GetAccessingUserId(request);

            // Generating tokens for each file
            var sasTokens = fileNames.Select(fileName =>
            {
                var blobFolder = container.GetBlobReference($"{userId}/{fileName}");
                return(blobFolder.GetSharedAccessSignature(policy));
            });

            return(new GetBlobSasTokenResponse
            {
                blobUri = storageAccount.BlobEndpoint.ToString(),
                containerName = ContainerName,
                folderName = userId,
                sasTokens = sasTokens.ToArray()
            });
        }
Ejemplo n.º 7
0
        public static string CreateOnlineTrainerCspkgBlobIfNotExists(string cspkgLink)
        {
            var    telemetry = new TelemetryClient();
            string azureStorageConnectionString = ConfigurationManager.AppSettings[AKConnectionString];
            var    storageAccount     = CloudStorageAccount.Parse(azureStorageConnectionString);
            var    blobClient         = storageAccount.CreateCloudBlobClient();
            var    armDeployContainer = blobClient.GetContainerReference(StorageARMDeployContainer);

            var cspkgBlob = armDeployContainer.GetBlockBlobReference(StorageOnlineTrainerPackageName);

            if (!cspkgBlob.Exists())
            {
                telemetry.TrackTrace("Online Trainer Package blob not found, creating new one.");
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                armDeployContainer.CreateIfNotExists();
                using (var wc = new WebClient())
                    using (var cspkgStream = new MemoryStream(wc.DownloadData(cspkgLink)))
                    {
                        cspkgBlob.UploadFromStream(cspkgStream);
                    }
            }
            else
            {
                telemetry.TrackTrace("Online Trainer Package already exists.");
            }
            var sasPolicy = new SharedAccessBlobPolicy
            {
                Permissions            = SharedAccessBlobPermissions.Read,
                SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-1),
                SharedAccessExpiryTime = DateTime.UtcNow.AddYears(1)
            };

            var uri = cspkgBlob.Uri.ToString() + cspkgBlob.GetSharedAccessSignature(sasPolicy);

            telemetry.TrackTrace($"Online Trainer Package URI: '{uri}'");

            return(uri);
        }
Ejemplo n.º 8
0
        public override void ExecuteCmdlet()
        {
            CloudBlob blob = null;

            if (ParameterSetName == BlobNamePipelineParmeterSetWithPermission ||
                ParameterSetName == BlobNamePipelineParmeterSetWithPolicy)
            {
                blob = GetCloudBlobByName(Container, Blob);
            }
            else
            {
                blob = this.CloudBlob;
            }

            SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
            bool shouldSetExpiryTime            = SasTokenHelper.ValidateContainerAccessPolicy(Channel, blob.Container.Name, accessPolicy, accessPolicyIdentifier);

            SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
            string sasToken = GetBlobSharedAccessSignature(blob, accessPolicy, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));

            if (FullUri)
            {
                string fullUri = blob.SnapshotQualifiedUri.ToString();
                if (blob.IsSnapshot)
                {
                    // Since snapshot URL already has '?', need remove '?' in the first char of sas
                    fullUri = fullUri + "&" + sasToken.Substring(1);
                }
                else
                {
                    fullUri = fullUri + sasToken;
                }
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Uploads the specified file to the specified Blob container.
        /// </summary>
        /// <param name="blobClient">A <see cref="CloudBlobClient"/>.</param>
        /// <param name="containerName">The name of the blob storage container to which the file should be uploaded.</param>
        /// <param name="filePath">The full path to the file to upload to Storage.</param>
        /// <returns>A ResourceFile instance representing the file within blob storage.</returns>
        private async static Task <ResourceFile> UploadFileToContainer(CloudBlobClient blobClient, string containerName, string filePath)
        {
            string blobName = Path.GetFileName(filePath);

            CloudBlobContainer container = blobClient.GetContainerReference(containerName);
            CloudBlockBlob     blobData  = container.GetBlockBlobReference(blobName);
            await blobData.UploadFromFileAsync(filePath);

            // Set the expiry time and permissions for the blob shared access signature. In this case, no start time is specified,
            // so the shared access signature becomes valid immediately
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(2),
                Permissions            = SharedAccessBlobPermissions.Read
            };

            // Construct the SAS URL for blob
            string sasBlobToken = blobData.GetSharedAccessSignature(sasConstraints);
            string blobSasUri   = String.Format("{0}{1}", blobData.Uri, sasBlobToken);

            return(new ResourceFile(blobSasUri, blobName));
        }
Ejemplo n.º 10
0
        private IEnumerable <GetModel> ResolvePhotoUri(IConfiguration configuration, IQueryable <GetModel> query)
        {
            var policy = new SharedAccessBlobPolicy
            {
                Permissions            = SharedAccessBlobPermissions.Read,
                SharedAccessExpiryTime = DateTimeOffset.Now.AddMinutes(10)
            };
            CloudBlobContainer historyContainer = GetHistoryContainer(configuration);

            return(query.AsEnumerable().Select(s =>
            {
                if (s.PhotoUri != null)
                {
                    CloudBlockBlob blob = historyContainer.GetBlockBlobReference(Path.GetFileName(s.PhotoUri));
                    string sas = blob.GetSharedAccessSignature(policy);

                    s.PhotoUri = blob.Uri + sas;
                }

                return s;
            }));
        }
        //[Route("api/getstoragetoken/UpAccess")]
        public async Task <StorageTokenViewModel> GetUpAccessAsync(string sharingSpaceId, string objectId)
        {
            // The userId is the SID without the sid: prefix
            //var claimsPrincipal = User as ClaimsPrincipal;
            //var userId = claimsPrincipal
            //    .FindFirst(ClaimTypes.NameIdentifier)
            //    .Value.Substring(4);

            string userId = Settings.GetUserId(User).Replace("|", "");

            // Errors creating the storage container result in a 500 Internal Server Error
            var container = BlobClient.GetContainerReference(containerName);
            await container.CreateIfNotExistsAsync();

            // Get the user directory within the container
            var directory             = container.GetDirectoryReference(userId);
            var sharingSpaceDirectory = directory.GetDirectoryReference(sharingSpaceId);
            //var blobName = Guid.NewGuid().ToString("N");
            var blobName = objectId;
            var blob     = sharingSpaceDirectory.GetBlockBlobReference(blobName + ".jpg");

            // Create a policy for accessing the defined blob
            var blobPolicy = new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(60),
                Permissions            = SharedAccessBlobPermissions.Read
                                         | SharedAccessBlobPermissions.Write
                                         | SharedAccessBlobPermissions.Create
            };

            return(new StorageTokenViewModel
            {
                Name = blobName,
                Uri = blob.Uri,
                SasToken = blob.GetSharedAccessSignature(blobPolicy)
            });
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates the download link.
        /// </summary>
        /// <param name="assetStorageProvider"></param>
        /// <param name="asset">The asset.</param>
        /// <returns></returns>
        public override string CreateDownloadLink(AssetStorageProvider assetStorageProvider, Asset asset)
        {
            string rootFolder = FixRootFolder(GetAttributeValue(assetStorageProvider, AttributeKey.RootFolder));

            asset.Key = FixKey(asset, rootFolder);
            HasRequirementsFile(asset);

            try
            {
                var container = GetCloudBlobContainer(assetStorageProvider);

                // Get a reference to a blob with a request to the server.
                // If the blob does not exist, this call will fail with a 404 (Not Found).
                var blob = container.GetBlobReferenceFromServer(asset.Key) as CloudBlob;

                // Create a new access policy and define its constraints.
                // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad-hoc SAS, and
                // to construct a shared access policy that is saved to the container's shared access policies.
                SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
                {
                    // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
                    // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
                    SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                    Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create
                };

                // Generate the shared access signature on the blob, setting the constraints directly on the signature.
                var sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);

                // Return the URI string for the container, including the SAS token.
                return(blob.Uri + sasBlobToken);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex);
                throw;
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// This will return up to 3 tokens for the storage accounts
        /// </summary>
        /// <returns></returns>
        private string[] GetContainerSasUris()
        {
            // We need to refresh the tokens every time or they will become invalid.
            tokens             = new string[3];
            containerAddresses = new string[3];

            string accountName = _configuration.GetSection("StorageAccountName")?.Value;
            string accountKey  = _configuration.GetSection("StorageAccountKey")?.Value;

            SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                Permissions            = SharedAccessBlobPermissions.Read
            };

            containerAddresses[0] = _configuration.GetSection("StorageContainerAddress")?.Value.ToLower();
            CloudBlobContainer container = new CloudBlobContainer(new Uri(containerAddresses[0]), new StorageCredentials(accountName, accountKey));

            tokens[0] = container.GetSharedAccessSignature(adHocPolicy, null);

            // Get token for second indexer data source
            containerAddresses[1] = _configuration.GetSection("StorageContainerAddress2")?.Value.ToLower();
            if (!String.Equals(containerAddresses[1], defaultContainerUriValue))
            {
                CloudBlobContainer container2 = new CloudBlobContainer(new Uri(containerAddresses[1]), new StorageCredentials(accountName, accountKey));
                tokens[1] = container2.GetSharedAccessSignature(adHocPolicy, null);
            }

            // Get token for third indexer data source
            containerAddresses[2] = _configuration.GetSection("StorageContainerAddress3")?.Value.ToLower();
            if (!String.Equals(containerAddresses[2], defaultContainerUriValue))
            {
                CloudBlobContainer container3 = new CloudBlobContainer(new Uri(containerAddresses[2]), new StorageCredentials(accountName, accountKey));
                tokens[2] = container3.GetSharedAccessSignature(adHocPolicy, null);
            }

            return(tokens);
        }
Ejemplo n.º 14
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.High, "Creating container named '{0}' in storage account {1}.", ContainerName, AccountName);

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AccountName, AccountKey));
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer  newContainer   = blobClient.GetContainerReference(ContainerName);

            if (FailIfExists && newContainer.Exists())
            {
                Log.LogError("The container '{0}' already exists.", ContainerName);
                return(false);
            }
            else
            {
                newContainer.CreateIfNotExists();
            }

            StorageUri = newContainer.Uri.ToString();

            if (ReadOnlyTokenDaysValid > 0)
            {
                var sasRO = new SharedAccessBlobPolicy();
                sasRO.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(ReadOnlyTokenDaysValid);
                sasRO.Permissions            = SharedAccessBlobPermissions.Read;
                ReadOnlyToken = newContainer.GetSharedAccessSignature(sasRO);
            }

            if (WriteOnlyTokenDaysValid > 0)
            {
                var sasWO = new SharedAccessBlobPolicy();
                sasWO.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(WriteOnlyTokenDaysValid);
                sasWO.Permissions            = SharedAccessBlobPermissions.Write;
                WriteOnlyToken = newContainer.GetSharedAccessSignature(sasWO);
            }

            return(true);
        }
Ejemplo n.º 15
0
        public Task <BlobSharedAccessInformation> GetBlobSharedAccessInformationForReadingAsync(string containerName, string blobName, DateTime expiry)
        {
            containerName.AssertNotNull("containerName");
            blobName.AssertNotNull("blobName");

            if (expiry.Kind != DateTimeKind.Utc)
            {
                throw new InvalidOperationException("Expiry time must be in UTC");
            }

            var client    = this.cloudStorageAccount.CreateCloudBlobClient();
            var container = client.GetContainerReference(containerName);
            var blob      = container.GetBlockBlobReference(blobName);

            var policy = new SharedAccessBlobPolicy
            {
                SharedAccessExpiryTime = expiry,
                Permissions            = SharedAccessBlobPermissions.Read
            };

            var token = blob.GetSharedAccessSignature(policy);

            var blobUri   = blob.Uri;
            var cdnDomain = this.azureConfiguration.CdnDomain;

            if (string.IsNullOrWhiteSpace(cdnDomain))
            {
                throw new InvalidOperationException("CDN domain has not been configured.");
            }

            var cdnUriBuilder = new UriBuilder(blobUri)
            {
                Host = cdnDomain
            };
            var cdnUri = cdnUriBuilder.Uri.GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped);

            return(Task.FromResult(new BlobSharedAccessInformation(containerName, blobName, cdnUri, token, expiry)));
        }
        public void ValidateSetupAccessPolicyPermissionTest()
        {
            SharedAccessBlobPolicy blobAccessPolicy = new SharedAccessBlobPolicy();

            AccessPolicyHelper.SetupAccessPolicyPermission(blobAccessPolicy, null);
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(blobAccessPolicy, "");
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(blobAccessPolicy, "D");
            Assert.AreEqual(blobAccessPolicy.Permissions, SharedAccessBlobPermissions.Delete);

            SharedAccessTablePolicy tableAccessPolicy = new SharedAccessTablePolicy();

            AccessPolicyHelper.SetupAccessPolicyPermission(tableAccessPolicy, null);
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(tableAccessPolicy, "");
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(tableAccessPolicy, "ar");
            Assert.AreEqual(tableAccessPolicy.Permissions, SharedAccessTablePermissions.Add | SharedAccessTablePermissions.Query);

            SharedAccessQueuePolicy queueAccessPolicy = new SharedAccessQueuePolicy();

            AccessPolicyHelper.SetupAccessPolicyPermission(queueAccessPolicy, null);
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(queueAccessPolicy, "");
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(queueAccessPolicy, "p");
            Assert.AreEqual(queueAccessPolicy.Permissions, SharedAccessQueuePermissions.ProcessMessages);

            SharedAccessFilePolicy fileAccessPolicy = new SharedAccessFilePolicy();

            AccessPolicyHelper.SetupAccessPolicyPermission(fileAccessPolicy, null);
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(fileAccessPolicy, "");
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.None);
            AccessPolicyHelper.SetupAccessPolicyPermission(fileAccessPolicy, "lwc");
            Assert.AreEqual(fileAccessPolicy.Permissions, SharedAccessFilePermissions.List | SharedAccessFilePermissions.Write | SharedAccessFilePermissions.Create);
        }
Ejemplo n.º 17
0
        private static async Task <HashSet <string> > GetBlobSasUri(CloudBlobContainer container, string policyName = null)
        {
            string sasBlobToken;
            var    resultSegment = await container.ListBlobsSegmentedAsync(null);

            var blobNames = new HashSet <string>();
            var blobsUrls = new HashSet <string>();

            foreach (IListBlobItem item in resultSegment.Results)
            {
                if (item.GetType() == typeof(CloudBlockBlob))
                {
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                    blobNames.Add(blob.Name);
                }

                foreach (var blobitem in blobNames)
                {
                    CloudBlockBlob blob = container.GetBlockBlobReference(blobitem);

                    if (policyName == null)
                    {
                        SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
                        {
                            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
                            Permissions            = SharedAccessBlobPermissions.Read
                        };
                        sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);
                    }
                    else
                    {
                        sasBlobToken = blob.GetSharedAccessSignature(null, policyName);
                    }
                    blobsUrls.Add(blob.Uri + sasBlobToken);
                }
            }
            return(blobsUrls);
        }
Ejemplo n.º 18
0
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name))
            {
                return;
            }
            CloudBlobContainer     container    = Channel.GetContainerReference(Name);
            SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
            bool shouldSetExpiryTime            = SasTokenHelper.ValidateContainerAccessPolicy(Channel, container.Name, accessPolicy, accessPolicyIdentifier);

            SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
            string sasToken = container.GetSharedAccessSignature(accessPolicy, accessPolicyIdentifier);

            if (FullUri)
            {
                string fullUri = container.Uri.ToString() + sasToken;
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
Ejemplo n.º 19
0
        public string GenerateSASToken(Uri docUri, string containerName)
        {
            CloudBlobClient    blobClient = _storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference(containerName);

            BlobContainerPermissions permissions = new BlobContainerPermissions();

            permissions.PublicAccess = BlobContainerPublicAccessType.Off;
            permissions.SharedAccessPolicies.Clear();
            permissions.SharedAccessPolicies.Add("twominutepolicy", new SharedAccessBlobPolicy());
            container.SetPermissionsAsync(permissions);

            SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-1),
                SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(2),
                Permissions            = SharedAccessBlobPermissions.Read
            };

            CloudBlockBlob blob = container.GetBlockBlobReference(docUri.ToString());

            return(blob.GetSharedAccessSignature(sharedPolicy, "twominutepolicy"));
        }
Ejemplo n.º 20
0
        public static string GenerateBlobSasToken(string connectionString, string inputContainerName, string inputBlobName)
        {
            var sourceStorageAccount = CloudStorageAccount.Parse(connectionString);
            // generate the sas token with write permission in customer's storage and pass it to the command worker role
            var sourceBlobClient = sourceStorageAccount.CreateCloudBlobClient();

            var container = sourceBlobClient.GetContainerReference(inputContainerName);
            var blob      = container.GetAppendBlobReference(inputBlobName);

            //Set the expiry time and permissions for the blob.
            //In this case the start time is specified as a few minutes in the past, to mitigate clock skew.
            //The shared access signature will be valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();

            sasConstraints.SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5);
            sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddHours(72);
            sasConstraints.Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write;

            //Generate the shared access signature on the blob, setting the constraints directly on the signature.
            string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            return(sasBlobToken);
        }
Ejemplo n.º 21
0
        public async Task <string> GetSecureUrl()
        {
            CloudBlobClient    blobClient = _storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container  = blobClient.GetContainerReference("signin");

            container.CreateIfNotExists();
            SharedAccessBlobPolicy blobPolicy = new SharedAccessBlobPolicy();

            blobPolicy.SharedAccessExpiryTime = DateTime.Now.AddHours(0.25d);
            blobPolicy.Permissions            = SharedAccessBlobPermissions.Read;
            BlobContainerPermissions blobPermissions = new BlobContainerPermissions();

            blobPermissions.SharedAccessPolicies.Add("ReadBlobPolicy", blobPolicy);
            blobPermissions.PublicAccess = BlobContainerPublicAccessType.Off;
            await container.SetPermissionsAsync(blobPermissions);

            string     sasToken  = container.GetSharedAccessSignature(new SharedAccessBlobPolicy(), "ReadBlobPolicy");
            ICloudBlob blob      = container.GetBlockBlobReference(_blobId);
            Uri        blobUrl   = blob.Uri;
            string     secureUrl = blobUrl.AbsoluteUri + sasToken;

            return(secureUrl);
        }
Ejemplo n.º 22
0
        public IActionResult ReceiptAuthorizationGet(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "authorizeReceipt")] HttpRequest request,
            [Blob("receipts", FileAccess.ReadWrite, Connection = "UploadStorage")] CloudBlobContainer container,
            ILogger log,
            ClaimsPrincipal principal
            )
        {
            var blob   = container.GetBlockBlobReference($"{_b2cHelper.GetOid(principal)}/{request.Query["name"]}");
            var policy = new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = DateTime.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
                Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write
            };
            var sas = blob.GetSharedAccessSignature(policy);

            log.LogInformation($"Authorized access to receipt \"{request.Query["name"]}\" for user {_b2cHelper.GetOid(principal)}");
            var authorization = new ReceiptAuthorizationDto {
                Url = $"{blob.Uri}{sas}"
            };

            return(new OkObjectResult(authorization));
        }
        /// <summary>
        /// Get a signed access url with an absolute expiry.
        /// </summary>
        /// <param name="blobPath">Blob to give access to.</param>
        /// <param name="signedAccessConfig">Access config including required permissions and expiry</param>
        /// <returns>String access url.</returns>
        public async Task <string> GetSignedBlobAccessUrl(string blobPath, ISignedAccessConfig signedAccessConfig)
        {
            var blobPolicyPermissions = GetAzureBlobPolicyPermissions(signedAccessConfig.AccessPermissions);
            var blob = GetBlockBlobReference(blobPath);

            var policy = new SharedAccessBlobPolicy
            {
                Permissions = blobPolicyPermissions
            };

            policy.SharedAccessStartTime = DateTime.Now.AddDays(-1);

            if (signedAccessConfig.AccessExpiry != null)
            {
                policy.SharedAccessExpiryTime = signedAccessConfig.AccessExpiry;
            }
            else
            {
                policy.SharedAccessExpiryTime = DateTime.Now.AddDays(365);
            }

            return(new Uri(blob.Uri, blob.GetSharedAccessSignature(policy)).ToString());
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Upload a file to Azure's cloud storage if it does not already exist.
        /// Return the URI and shared access signature of the uploaded blob.
        /// </summary>
        /// <param name="containerName">Name of the container to upload the file to</param>
        /// <param name="filePath">Path to the file on disk</param>
        private async Task<string> UploadFileIfNeededAsync(string containerName, string filePath, CancellationToken ct)
        {
            CloudBlobContainer container = storageClient.GetContainerReference(containerName);
            await container.CreateIfNotExistsAsync(ct);
            CloudBlockBlob blob = container.GetBlockBlobReference(Path.GetFileName(filePath));

            string md5 = GetFileMd5(filePath);
            
            // If blob already exists and md5 matches, there is no need to upload the file.
            if (await blob.ExistsAsync(ct) && string.Equals(md5, blob.Properties.ContentMD5, StringComparison.InvariantCultureIgnoreCase))
                return null;

            blob.Properties.ContentMD5 = md5;
            await blob.UploadFromFileAsync(filePath, ct);

            var policy = new SharedAccessBlobPolicy
            {
                Permissions = SharedAccessBlobPermissions.Read,
                SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-15),
                SharedAccessExpiryTime = DateTime.UtcNow.AddMonths(12) // Hopefully this job won't take more than a year!
            };
            return blob.Uri.AbsoluteUri + blob.GetSharedAccessSignature(policy);
        }
        private static dynamic _getBlobUriWithSasTokenAndMD5(string blobPath, CloudBlobContainer blobContainer)
        {
            if (string.IsNullOrEmpty(blobPath))
            {
                return(new { blobSasToken = string.Empty, blobMD5 = string.Empty });
            }

            var blob = blobContainer.GetBlockBlobReference(blobPath);

            var sasConstraints =
                new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddHours(24),
                Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write
            };

            var sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            blob.FetchAttributesAsync().GetAwaiter().GetResult();

            return(new { blobSasToken = blob.Uri + sasBlobToken, blobMD5 = blob.Properties.ContentMD5 });
        }
Ejemplo n.º 26
0
        private string GetBlobSasUri(string containerName, string BlobName)
        {
            //Get a reference to a blob within the container.
            CloudBlobContainer container = _WaterMArkStorageBlobClient.GetContainerReference(containerName);

            container.CreateIfNotExists();
            CloudBlockBlob         blob           = container.GetBlockBlobReference(BlobName);
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddHours(48),
                Permissions            =
                    SharedAccessBlobPermissions.Read |
                    SharedAccessBlobPermissions.Write |
                    SharedAccessBlobPermissions.Add |
                    SharedAccessBlobPermissions.Create
            };

            string sasBlobToken = blob.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            return(blob.Uri + sasBlobToken);
        }
        private static async Task <string> GetBlobContainerUriWithSas(string blobContainerName)
        {
            var storageAccount = CloudStorageAccount.Parse(exportStorageAccountConnectionString);
            var blobClient     = storageAccount.CreateCloudBlobClient();
            var blobContainer  = blobClient.GetContainerReference(blobContainerName);

            await blobContainer.CreateIfNotExistsAsync();

            var sasPolicy = new SharedAccessBlobPolicy
            {
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
                Permissions            =
                    SharedAccessBlobPermissions.Write |
                    SharedAccessBlobPermissions.Read |
                    SharedAccessBlobPermissions.Delete
            };

            var sas = blobContainer.GetSharedAccessSignature(sasPolicy);

            var sasUri = blobContainer.Uri + sas;

            return(sasUri);
        }
Ejemplo n.º 28
0
        public string GetImageUrlWithSAS(string fileName, string blobStorageFolder)
        {
            var blobReference = _getAzureFile.GetAzureBlobFileReference(fileName, blobStorageFolder);
            var name          = blobReference.Name;

            //Set the expiry time and permissions for the blob.
            //In this case, the start time is specified as a minute in the past, to mitigate clock skew.
            //The shared access signature will be valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-1),
                Permissions            = SharedAccessBlobPermissions.Read,
                SharedAccessExpiryTime = DateTime.UtcNow.AddSeconds(30)
            };

            //Generate the shared access signature on the blob, setting the constraints directly on the blob.
            string sasBlobToken = blobReference.GetSharedAccessSignature(sasConstraints);

            //Return the URI string for the container, including the SAS token.
            var uri = blobReference.Uri.AbsoluteUri + sasBlobToken;

            return(uri);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Get blob shared access signature
        /// </summary>
        /// <param name="blob">ICloudBlob object</param>
        /// <param name="accessPolicy">SharedAccessBlobPolicy object</param>
        /// <param name="policyIdentifier">The existing policy identifier.</param>
        /// <returns></returns>
        private string GetBlobSharedAccessSignature(ICloudBlob blob, SharedAccessBlobPolicy accessPolicy, string policyIdentifier)
        {
            CloudBlobContainer container = blob.Container;
            string             signature = String.Empty;

            switch (blob.BlobType)
            {
            case BlobType.BlockBlob:
                CloudBlockBlob blockBlob = blob as CloudBlockBlob;
                signature = blockBlob.GetSharedAccessSignature(accessPolicy, policyIdentifier);
                break;

            case BlobType.PageBlob:
                CloudPageBlob pageBlob = blob as CloudPageBlob;
                signature = pageBlob.GetSharedAccessSignature(accessPolicy, policyIdentifier);
                break;

            default:
                throw new ArgumentException(Resources.UnknownBlob);
            }

            return(signature);
        }
Ejemplo n.º 30
0
        private async Task <Uri> CreateBlobSas(string filePath, string blobContainer, string blobName)
        {
            var    configuration               = _httpServer.Host.Services.GetService <IConfiguration>();
            string connectionString            = configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage);
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
            var blobClient = storageAccount.CreateCloudBlobClient();
            var container  = blobClient.GetContainerReference(blobContainer);
            await container.CreateIfNotExistsAsync();

            var blob = container.GetBlockBlobReference(blobName);
            await blob.UploadFromFileAsync(filePath);

            var policy = new SharedAccessBlobPolicy
            {
                SharedAccessStartTime  = DateTime.UtcNow,
                SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
                Permissions            = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List
            };
            var sas    = blob.GetSharedAccessSignature(policy);
            var sasUri = new Uri(blob.Uri, sas);

            return(sasUri);
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            //Open the dialog box
            System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
            dialog.InitialDirectory = "C:/";
            dialog.Multiselect = true;
            dialog.RestoreDirectory = true;
            System.Windows.Forms.DialogResult Result = dialog.ShowDialog();

            string[] files;
            //Load the image to the load image picture box
            if (Result == System.Windows.Forms.DialogResult.OK)
            {
                files = dialog.FileNames;

                string blobUri = SettingsValues.BLOB_URL;
                string key = SettingsValues.BLOB_KEY;
                string account = SettingsValues.BLOB_ACCOUNT;
                StorageCredentialsAccountAndKey credentials = new StorageCredentialsAccountAndKey(account, key);
                CloudBlobClient client = new CloudBlobClient(blobUri, credentials);

                string containerName = "container";
                CloudBlobContainer blobContainer = client.GetContainerReference(containerName);
                bool created = blobContainer.CreateIfNotExist();

                resourceFiles = new List<ResourceFile>();

                foreach (string strFile in files)
                {
                    string[] chunks = strFile.Split('\\');
                    string blobName = chunks[chunks.Length - 1];
                    string filePath = strFile.Substring(0, strFile.Length - blobName.Length);

                    CloudBlob blob = blobContainer.GetBlobReference(blobName);
                    //System.Windows.MessageBox.Show(string.Format("filepath: {0}", strFile));
                    blob.UploadFile(strFile);

                    SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy();
                    policy.Permissions = SharedAccessBlobPermissions.Read;
                    policy.SharedAccessExpiryTime = DateTime.Now.AddHours(1);
                    
                    string token = blob.GetSharedAccessSignature(policy);
                    string resourceBlobPath = blobUri + "/" + containerName + "/" + blobName + token;

                    System.Windows.MessageBox.Show("Uploading file complete");

                    DataRow row = dataTable1.NewRow(); ;
                    row.ItemArray = new object[]{blobName, resourceBlobPath};
                    dataView1.Table.Rows.Add(row);
                }
            }
        }