/// <summary> /// Get blob's SaS Uri /// </summary> /// <param name="blob"></param> /// <param name="permissionType"></param> /// <returns></returns> public string GetContainerBlobUri(CloudBlockBlob blob, string permissionType) { SharedAccessBlobPolicy sasConstraints = CreateSASPermission(permissionType); //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 blob.Uri + sasBlobToken; }
string GetBlobSasUri(Microsoft.WindowsAzure.Storage.Blob.CloudBlockBlob blockBlob) { SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy(); sasConstraints.SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5); sasConstraints.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddHours(24); sasConstraints.Permissions = SharedAccessBlobPermissions.Read; string sasBlobToken = blockBlob.GetSharedAccessSignature(sasConstraints); return(blockBlob.Uri + sasBlobToken); }
/// <summary> /// Generate a blob SAS /// </summary> /// <param name="blob">CloudBlockBlob</param> /// <returns>SAS string for the specified CLoudBlockBlob</returns> private static string GetSasForBlob(CloudBlockBlob blob) { if (blob == null) { throw new ArgumentNullException("blob can't be null"); } var sas = blob.GetSharedAccessSignature( new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List, SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(30), }); return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas); }
public void CloudBlobContainerGetBlobReferenceFromServerAPM() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); pageBlob.Create(0); using (AutoResetEvent waitHandle = new AutoResetEvent(false)) { IAsyncResult result = container.BeginGetBlobReferenceFromServer("bb", ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob1 = container.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob)); result = ((CloudBlockBlob)blob1).BeginCreateSnapshot( ar => waitHandle.Set(), null); waitHandle.WaitOne(); CloudBlockBlob blob1Snapshot = ((CloudBlockBlob)blob1).EndCreateSnapshot(result); result = blob1.BeginSetProperties( ar => waitHandle.Set(), null); waitHandle.WaitOne(); blob1.EndSetProperties(result); Uri blob1SnapshotUri = new Uri(blob1Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob1Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blob1SnapshotUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob1SnapshotReference = container.ServiceClient.EndGetBlobReferenceFromServer(result); AssertAreEqual(blob1Snapshot.Properties, blob1SnapshotReference.Properties); result = container.BeginGetBlobReferenceFromServer("pb", ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob2 = container.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob)); result = ((CloudPageBlob)blob2).BeginCreateSnapshot( ar => waitHandle.Set(), null); waitHandle.WaitOne(); CloudPageBlob blob2Snapshot = ((CloudPageBlob)blob2).EndCreateSnapshot(result); result = blob2.BeginSetProperties( ar => waitHandle.Set(), null); waitHandle.WaitOne(); blob2.EndSetProperties(result); Uri blob2SnapshotUri = new Uri(blob2Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob2Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blob2SnapshotUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob2SnapshotReference = container.ServiceClient.EndGetBlobReferenceFromServer(result); AssertAreEqual(blob2Snapshot.Properties, blob2SnapshotReference.Properties); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlob.Uri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob3 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob)); result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlob.Uri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob4 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob4, typeof(CloudPageBlob)); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); result = container.ServiceClient.BeginGetBlobReferenceFromServer(blockBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob5 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob)); result = container.ServiceClient.BeginGetBlobReferenceFromServer(pageBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob6 = container.ServiceClient.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob)); CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS); result = client7.BeginGetBlobReferenceFromServer(blockBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob7 = client7.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob)); CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS); result = client8.BeginGetBlobReferenceFromServer(pageBlobSASUri, ar => waitHandle.Set(), null); waitHandle.WaitOne(); ICloudBlob blob8 = client8.EndGetBlobReferenceFromServer(result); Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob)); } } finally { container.DeleteIfExists(); } }
public async Task CloudBlobContainerGetBlobReferenceFromServerAsync() { CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); await blockBlob.PutBlockListAsync(new List <string>()); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); await pageBlob.CreateAsync(0); CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab"); await appendBlob.CreateOrReplaceAsync(); CloudBlobClient client; ICloudBlob blob; blob = await container.GetBlobReferenceFromServerAsync("bb"); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); CloudBlockBlob blockBlobSnapshot = await((CloudBlockBlob)blob).CreateSnapshotAsync(); await blob.SetPropertiesAsync(); Uri blockBlobSnapshotUri = new Uri(blockBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + blockBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSnapshotUri); AssertAreEqual(blockBlobSnapshot.Properties, blob.Properties); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlobSnapshot.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.GetBlobReferenceFromServerAsync("pb"); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); CloudPageBlob pageBlobSnapshot = await((CloudPageBlob)blob).CreateSnapshotAsync(); await blob.SetPropertiesAsync(); Uri pageBlobSnapshotUri = new Uri(pageBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + pageBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSnapshotUri); AssertAreEqual(pageBlobSnapshot.Properties, blob.Properties); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlobSnapshot.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.GetBlobReferenceFromServerAsync("ab"); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); CloudAppendBlob appendBlobSnapshot = await((CloudAppendBlob)blob).CreateSnapshotAsync(); await blob.SetPropertiesAsync(); Uri appendBlobSnapshotUri = new Uri(appendBlobSnapshot.Uri.AbsoluteUri + "?snapshot=" + appendBlobSnapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSnapshotUri); AssertAreEqual(appendBlobSnapshot.Properties, blob.Properties); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlobSnapshot.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.Uri); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.StorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.StorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlob.StorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); string appendBlobToken = appendBlob.GetSharedAccessSignature(policy); StorageCredentials appendBlobSAS = new StorageCredentials(appendBlobToken); Uri appendBlobSASUri = appendBlobSAS.TransformUri(appendBlob.Uri); StorageUri appendBlobSASStorageUri = appendBlobSAS.TransformUri(appendBlob.StorageUri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); blob = await container.ServiceClient.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); client = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); client = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); client = new CloudBlobClient(container.ServiceClient.BaseUri, appendBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(appendBlobSASUri); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(appendBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); client = new CloudBlobClient(container.ServiceClient.StorageUri, blockBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(blockBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); client = new CloudBlobClient(container.ServiceClient.StorageUri, pageBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(pageBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); client = new CloudBlobClient(container.ServiceClient.StorageUri, appendBlobSAS); blob = await client.GetBlobReferenceFromServerAsync(appendBlobSASStorageUri, null, null, null); Assert.IsInstanceOfType(blob, typeof(CloudAppendBlob)); Assert.IsTrue(blob.StorageUri.Equals(appendBlob.StorageUri)); } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
private String getSasForBlob(StorageCredentials credentials, String blobUri, String verb) { CloudBlockBlob blob = new CloudBlockBlob(new Uri(blobUri), credentials); var permission = SharedAccessBlobPermissions.Write; if (verb == "DELETE") { permission = SharedAccessBlobPermissions.Delete; } var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy() { Permissions = permission, SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(15), }); return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas); }
public string GetSasForBlob(CloudBlockBlob blob, SharedAccessBlobPermissions permission) { var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy() { Permissions = permission, SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(2), }); return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas); }
public void CloudBlobSASSharedProtocolsQueryParam() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); foreach (SharedAccessProtocol?protocol in new SharedAccessProtocol?[] { null, SharedAccessProtocol.HttpsOrHttp, SharedAccessProtocol.HttpsOnly }) { string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, protocol, null); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = new Uri(blockBlob.Uri + blockBlobSAS.SASToken); StorageUri blockBlobSASStorageUri = new StorageUri(new Uri(blockBlob.StorageUri.PrimaryUri + blockBlobSAS.SASToken), new Uri(blockBlob.StorageUri.SecondaryUri + blockBlobSAS.SASToken)); int httpPort = blockBlobSASUri.Port; int securePort = 443; if (!string.IsNullOrEmpty(TestBase.TargetTenantConfig.BlobSecurePortOverride)) { securePort = Int32.Parse(TestBase.TargetTenantConfig.BlobSecurePortOverride); } var schemesAndPorts = new[] { new { scheme = Uri.UriSchemeHttp, port = httpPort }, new { scheme = Uri.UriSchemeHttps, port = securePort } }; foreach (var item in schemesAndPorts) { blockBlobSASUri = TransformSchemeAndPort(blockBlobSASUri, item.scheme, item.port); blockBlobSASStorageUri = new StorageUri(TransformSchemeAndPort(blockBlobSASStorageUri.PrimaryUri, item.scheme, item.port), TransformSchemeAndPort(blockBlobSASStorageUri.SecondaryUri, item.scheme, item.port)); if (protocol.HasValue && protocol.Value == SharedAccessProtocol.HttpsOnly && string.CompareOrdinal(item.scheme, Uri.UriSchemeHttp) == 0) { blob = new CloudBlob(blockBlobSASUri); TestHelper.ExpectedException(() => blob.FetchAttributes(), "Access a blob using SAS with a shared protocols that does not match", HttpStatusCode.Unused); blob = new CloudBlob(blockBlobSASStorageUri, null, null); TestHelper.ExpectedException(() => blob.FetchAttributes(), "Access a blob using SAS with a shared protocols that does not match", HttpStatusCode.Unused); } else { blob = new CloudBlob(blockBlobSASUri); blob.FetchAttributes(); Assert.AreEqual(blob.BlobType, BlobType.BlockBlob); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.FetchAttributes(); Assert.AreEqual(blob.BlobType, BlobType.BlockBlob); } } } } finally { container.DeleteIfExists(); } }
/// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for blobs /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 }; blockBlob.UploadFromByteArray(data, 0, 4); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); byte[] target = new byte[4]; OperationContext opContext = new OperationContext(); IPAddress actualIP = null; opContext.ResponseReceived += (sender, e) => { Stream stream = e.Response.GetResponseStream(); stream.Seek(0, SeekOrigin.Begin); using (StreamReader reader = new StreamReader(stream)) { string text = reader.ReadToEnd(); XDocument xdocument = XDocument.Parse(text); actualIP = IPAddress.Parse(xdocument.Descendants("SourceIP").First().Value); } }; bool exceptionThrown = false; try { blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext); } catch (StorageException) { exceptionThrown = true; Assert.IsNotNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = generateFinalIPAddressOrRange(actualIP); blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); blockBlobSAS = new StorageCredentials(blockBlobToken); blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
public void CloudBlobSASApiVersionQueryParam() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); pageBlob.Create(0); CloudAppendBlob appendBlob = container.GetAppendBlobReference("ab"); appendBlob.CreateOrReplace(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri); string appendBlobToken = appendBlob.GetSharedAccessSignature(policy); StorageCredentials appendBlobSAS = new StorageCredentials(appendBlobToken); Uri appendBlobSASUri = appendBlobSAS.TransformUri(appendBlob.Uri); StorageUri appendBlobSASStorageUri = appendBlobSAS.TransformUri(appendBlob.StorageUri); OperationContext apiVersionCheckContext = new OperationContext(); apiVersionCheckContext.SendingRequest += (sender, e) => { Assert.IsTrue(e.Request.RequestUri.Query.Contains("api-version")); }; blob = new CloudBlob(blockBlobSASUri); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.BlockBlob); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(pageBlobSASUri); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.PageBlob); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.BlockBlob); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = new CloudBlob(pageBlobSASStorageUri, null, null); blob.FetchAttributes(operationContext: apiVersionCheckContext); Assert.AreEqual(blob.BlobType, BlobType.PageBlob); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
public void CloudBlobSASApiVersionQueryParam() { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); ICloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); blockBlob.PutBlockList(new string[] { }); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); pageBlob.Create(0); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); StorageUri pageBlobSASStorageUri = pageBlobSAS.TransformUri(pageBlob.StorageUri); OperationContext apiVersionCheckContext = new OperationContext(); apiVersionCheckContext.SendingRequest += (sender, e) => { Assert.IsNull(e.Request.Headers.Get("x-ms-version")); Assert.IsTrue(e.Request.RequestUri.Query.Contains("api-version")); }; blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(pageBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = container.ServiceClient.GetBlobReferenceFromServer(blockBlobSASStorageUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudBlockBlob)); Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); blob = container.ServiceClient.GetBlobReferenceFromServer(pageBlobSASStorageUri, operationContext: apiVersionCheckContext); Assert.IsInstanceOfType(blob, typeof(CloudPageBlob)); Assert.IsTrue(blob.StorageUri.Equals(pageBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
/// <summary> /// Helper function for testing the IPAddressOrRange funcitonality for blobs /// </summary> /// <param name="generateInitialIPAddressOrRange">Function that generates an initial IPAddressOrRange object to use. This is expected to fail on the service.</param> /// <param name="generateFinalIPAddressOrRange">Function that takes in the correct IP address (according to the service) and returns the IPAddressOrRange object /// that should be accepted by the service</param> public void CloudBlobSASIPAddressHelper(Func <IPAddressOrRange> generateInitialIPAddressOrRange, Func <IPAddress, IPAddressOrRange> generateFinalIPAddressOrRange) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); CloudBlob blob; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); byte[] data = new byte[] { 0x1, 0x2, 0x3, 0x4 }; blockBlob.UploadFromByteArray(data, 0, 4); // The plan then is to use an incorrect IP address to make a call to the service // ensure that we get an error message // parse the error message to get my actual IP (as far as the service sees) // then finally test the success case to ensure we can actually make requests IPAddressOrRange ipAddressOrRange = generateInitialIPAddressOrRange(); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); StorageUri blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); byte[] target = new byte[4]; OperationContext opContext = new OperationContext(); IPAddress actualIP = null; bool exceptionThrown = false; try { blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, opContext); } catch (StorageException) { exceptionThrown = true; //The IP should not be included in the error details for security reasons Assert.IsNull(actualIP); } Assert.IsTrue(exceptionThrown); ipAddressOrRange = null; blockBlobToken = blockBlob.GetSharedAccessSignature(policy, null, null, null, ipAddressOrRange); blockBlobSAS = new StorageCredentials(blockBlobToken); blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); blockBlobSASStorageUri = blockBlobSAS.TransformUri(blockBlob.StorageUri); blob = new CloudBlob(blockBlobSASUri); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.PrimaryUri.Equals(blockBlob.Uri)); Assert.IsNull(blob.StorageUri.SecondaryUri); blob = new CloudBlob(blockBlobSASStorageUri, null, null); blob.DownloadRangeToByteArray(target, 0, 0, 4, null, null, null); for (int i = 0; i < 4; i++) { Assert.AreEqual(data[i], target[i]); } Assert.IsTrue(blob.StorageUri.Equals(blockBlob.StorageUri)); } finally { container.DeleteIfExists(); } }
private static void CloudBlockBlobCopy(bool sourceIsSas, bool destinationIsSas) { CloudBlobContainer container = GetRandomContainerReference(); try { container.Create(); // Create Source on server CloudBlockBlob source = container.GetBlockBlobReference("source"); string data = "String data"; UploadText(source, data, Encoding.UTF8); source.Metadata["Test"] = "value"; source.SetMetadata(); // Create Destination on server CloudBlockBlob destination = container.GetBlockBlobReference("destination"); destination.PutBlockList(new string[] { }); CloudBlockBlob copySource = source; CloudBlockBlob copyDestination = destination; if (sourceIsSas) { // Source SAS must have read permissions SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Read; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = source.GetSharedAccessSignature(policy); // Get source StorageCredentials credentials = new StorageCredentials(sasToken); copySource = new CloudBlockBlob(credentials.TransformUri(source.Uri)); } if (destinationIsSas) { if (!sourceIsSas) { // Source container must be public if source is not SAS BlobContainerPermissions containerPermissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }; container.SetPermissions(containerPermissions); } // Destination SAS must have write permissions SharedAccessBlobPermissions permissions = SharedAccessBlobPermissions.Write; SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), Permissions = permissions, }; string sasToken = destination.GetSharedAccessSignature(policy); // Get destination StorageCredentials credentials = new StorageCredentials(sasToken); copyDestination = new CloudBlockBlob(credentials.TransformUri(destination.Uri)); } // Start copy and wait for completion string copyId = copyDestination.StartCopyFromBlob(TestHelper.Defiddler(copySource)); WaitForCopy(destination); // Check original blob references for equality Assert.AreEqual(CopyStatus.Success, destination.CopyState.Status); Assert.AreEqual(source.Uri.AbsolutePath, destination.CopyState.Source.AbsolutePath); Assert.AreEqual(data.Length, destination.CopyState.TotalBytes); Assert.AreEqual(data.Length, destination.CopyState.BytesCopied); Assert.AreEqual(copyId, destination.CopyState.CopyId); Assert.IsTrue(destination.CopyState.CompletionTime > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); if (!destinationIsSas) { // Abort Copy is not supported for SAS destination TestHelper.ExpectedException( () => copyDestination.AbortCopy(copyId), "Aborting a copy operation after completion should fail", HttpStatusCode.Conflict, "NoPendingCopyOperation"); } source.FetchAttributes(); Assert.IsNotNull(destination.Properties.ETag); Assert.AreNotEqual(source.Properties.ETag, destination.Properties.ETag); Assert.IsTrue(destination.Properties.LastModified > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromMinutes(1))); string copyData = DownloadText(destination, Encoding.UTF8); Assert.AreEqual(data, copyData, "Data inside copy of blob not equal."); destination.FetchAttributes(); BlobProperties prop1 = destination.Properties; BlobProperties prop2 = source.Properties; Assert.AreEqual(prop1.CacheControl, prop2.CacheControl); Assert.AreEqual(prop1.ContentEncoding, prop2.ContentEncoding); Assert.AreEqual(prop1.ContentLanguage, prop2.ContentLanguage); Assert.AreEqual(prop1.ContentMD5, prop2.ContentMD5); Assert.AreEqual(prop1.ContentType, prop2.ContentType); Assert.AreEqual("value", destination.Metadata["Test"], false, "Copied metadata not same"); destination.Delete(); source.Delete(); } finally { container.DeleteIfExists(); } }
public async Task CloudBlobContainerGetBlobReferenceFromServerAsync() { CloudBlobContainer container = GetRandomContainerReference(); try { await container.CreateAsync(); SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy() { Permissions = SharedAccessBlobPermissions.Read, SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5), SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30), }; CloudBlockBlob blockBlob = container.GetBlockBlobReference("bb"); await blockBlob.PutBlockListAsync(new List <string>()); CloudPageBlob pageBlob = container.GetPageBlobReference("pb"); await pageBlob.CreateAsync(0); ICloudBlob blob1 = await container.GetBlobReferenceFromServerAsync("bb"); Assert.IsInstanceOfType(blob1, typeof(CloudBlockBlob)); CloudBlockBlob blob1Snapshot = await((CloudBlockBlob)blob1).CreateSnapshotAsync(); await blob1.SetPropertiesAsync(); Uri blob1SnapshotUri = new Uri(blob1Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob1Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); ICloudBlob blob1SnapshotReference = await container.ServiceClient.GetBlobReferenceFromServerAsync(blob1SnapshotUri); AssertAreEqual(blob1Snapshot.Properties, blob1SnapshotReference.Properties); ICloudBlob blob2 = await container.GetBlobReferenceFromServerAsync("pb"); Assert.IsInstanceOfType(blob2, typeof(CloudPageBlob)); CloudPageBlob blob2Snapshot = await((CloudPageBlob)blob2).CreateSnapshotAsync(); await blob2.SetPropertiesAsync(); Uri blob2SnapshotUri = new Uri(blob2Snapshot.Uri.AbsoluteUri + "?snapshot=" + blob2Snapshot.SnapshotTime.Value.UtcDateTime.ToString("o")); ICloudBlob blob2SnapshotReference = await container.ServiceClient.GetBlobReferenceFromServerAsync(blob2SnapshotUri); AssertAreEqual(blob2Snapshot.Properties, blob2SnapshotReference.Properties); ICloudBlob blob3 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlob.Uri); Assert.IsInstanceOfType(blob3, typeof(CloudBlockBlob)); ICloudBlob blob4 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlob.Uri); Assert.IsInstanceOfType(blob4, typeof(CloudPageBlob)); string blockBlobToken = blockBlob.GetSharedAccessSignature(policy); StorageCredentials blockBlobSAS = new StorageCredentials(blockBlobToken); Uri blockBlobSASUri = blockBlobSAS.TransformUri(blockBlob.Uri); string pageBlobToken = pageBlob.GetSharedAccessSignature(policy); StorageCredentials pageBlobSAS = new StorageCredentials(pageBlobToken); Uri pageBlobSASUri = pageBlobSAS.TransformUri(pageBlob.Uri); ICloudBlob blob5 = await container.ServiceClient.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob5, typeof(CloudBlockBlob)); ICloudBlob blob6 = await container.ServiceClient.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob6, typeof(CloudPageBlob)); CloudBlobClient client7 = new CloudBlobClient(container.ServiceClient.BaseUri, blockBlobSAS); ICloudBlob blob7 = await client7.GetBlobReferenceFromServerAsync(blockBlobSASUri); Assert.IsInstanceOfType(blob7, typeof(CloudBlockBlob)); CloudBlobClient client8 = new CloudBlobClient(container.ServiceClient.BaseUri, pageBlobSAS); ICloudBlob blob8 = await client8.GetBlobReferenceFromServerAsync(pageBlobSASUri); Assert.IsInstanceOfType(blob8, typeof(CloudPageBlob)); } finally { container.DeleteIfExistsAsync().AsTask().Wait(); } }
public string GetSaSForBlob(CloudBlockBlob blob, string policyId) { var sas = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy(), policyId); return string.Format(CultureInfo.InvariantCulture, "{0}{1}", blob.Uri, sas); }
private string UploadImage(string encodedImage) { // Retrieve storage account from connection string. CloudStorageAccount storageAccount = CloudStorageAccount.Parse( ""); //Sensitive information was replaced with ** from the above string for protection // Create the blob client. CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Retrieve reference to a previously created container. CloudBlobContainer container = blobClient.GetContainerReference("images"); //Create the "images" container if it doesn't already exist. container.CreateIfNotExists(); // Retrieve reference to a blob with this name //Images will be saved in the format "image_[Guid][Date]" blockBlob = container.GetBlockBlobReference("image_" + Guid.NewGuid() + System.DateTime.Now); byte[] imageBytes = Convert.FromBase64String(encodedImage); // create or overwrite the blob named "image_" and the current date and time blockBlob.UploadFromByteArray(imageBytes, 0, imageBytes.Length); //Set the expiry time and permissions for the blob. //Start time is not specified meaning that this SAS is activated immediately SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy(); //Access is Valid for a week sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddDays(7); sasConstraints.Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write; //Generate the shared access signature on the blob, setting the constraints directly on the signature. string sasBlobToken = blockBlob.GetSharedAccessSignature(sasConstraints); //Return the URI string for the container, including the SAS token. return blockBlob.Uri + sasBlobToken; }