Exemplo n.º 1
2
        private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob)
        {
            CloudBlob SASblob;
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                new StorageCredentials() :
                new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(credentials.TransformUri(container.Uri));
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    SASblob = container.GetBlockBlobReference(blob.Name);
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    SASblob = container.GetPageBlobReference(blob.Name);
                }
                else
                {
                    SASblob = container.GetAppendBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    SASblob = new CloudBlockBlob(credentials.TransformUri(blob.Uri));
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    SASblob = new CloudPageBlob(credentials.TransformUri(blob.Uri));
                }
                else
                {
                    SASblob = new CloudAppendBlob(credentials.TransformUri(blob.Uri));
                }
            }

            HttpStatusCode failureCode = sasToken == null ? HttpStatusCode.NotFound : HttpStatusCode.Forbidden;

            // We want to ensure that 'create', 'add', and 'write' permissions all allow for correct writing of blobs, as is reasonable.
            if (((permissions & SharedAccessBlobPermissions.Create) == SharedAccessBlobPermissions.Create) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
            {
                if (blob.BlobType == BlobType.PageBlob)
                {
                    CloudPageBlob SASpageBlob = (CloudPageBlob)SASblob;
                    SASpageBlob.Create(512);
                    CloudPageBlob pageBlob = (CloudPageBlob)blob;
                    byte[] buffer = new byte[512];
                    buffer[0] = 2;  // random data

                    if (((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
                    {
                        SASpageBlob.UploadFromByteArray(buffer, 0, 512);
                    }
                    else
                    {
                        TestHelper.ExpectedException(
                            () => SASpageBlob.UploadFromByteArray(buffer, 0, 512),
                            "pageBlob SAS token without Write perms should not allow for writing/adding",
                            failureCode);
                        pageBlob.UploadFromByteArray(buffer, 0, 512);
                    }
                }
                else if (blob.BlobType == BlobType.BlockBlob)
                {
                    if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
                    {
                        UploadText(SASblob, "blob", Encoding.UTF8);
                    }
                    else
                    {
                        TestHelper.ExpectedException(
                            () => UploadText(SASblob, "blob", Encoding.UTF8),
                            "Block blob SAS token without Write or perms should not allow for writing",
                            failureCode);
                        UploadText(blob, "blob", Encoding.UTF8);
                    }
                }
                else // append blob
                {
                    // If the sas token contains Feb 2012, append won't be accepted 
                    if (sasToken.Contains(Constants.VersionConstants.February2012))
                    {
                        UploadText(blob, "blob", Encoding.UTF8);
                    }
                    else
                    {
                        CloudAppendBlob SASAppendBlob = SASblob as CloudAppendBlob;
                        SASAppendBlob.CreateOrReplace();

                        byte[] textAsBytes = Encoding.UTF8.GetBytes("blob");
                        using (MemoryStream stream = new MemoryStream())
                        {
                            stream.Write(textAsBytes, 0, textAsBytes.Length);
                            stream.Seek(0, SeekOrigin.Begin);

                            if (((permissions & SharedAccessBlobPermissions.Add) == SharedAccessBlobPermissions.Add) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
                            {
                                SASAppendBlob.AppendBlock(stream, null);
                            }
                            else
                            {
                                TestHelper.ExpectedException(
                                    () => SASAppendBlob.AppendBlock(stream, null),
                                    "Append blob SAS token without Write or Add perms should not allow for writing/adding",
                                    failureCode);
                                stream.Seek(0, SeekOrigin.Begin);
                                ((CloudAppendBlob)blob).AppendBlock(stream, null);
                            }
                        }
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                        () => UploadText(SASblob, "blob", Encoding.UTF8),
                        "UploadText SAS does not allow for writing/adding",
                        ((blob.BlobType == BlobType.AppendBlob) && (sasToken != null) && (sasToken.Contains(Constants.VersionConstants.February2012))) ? HttpStatusCode.BadRequest : failureCode);
                UploadText(blob, "blob", Encoding.UTF8);
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    container.ListBlobs().ToArray();
                }
                else
                {
                    TestHelper.ExpectedException(
                        () => container.ListBlobs().ToArray(),
                        "List blobs while SAS does not allow for listing",
                        failureCode);
                }
            }

            // need to have written to the blob to read from it.
            if (((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read))
            {
                SASblob.FetchAttributes();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, SASblob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, SASblob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, SASblob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, SASblob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, SASblob.Properties.ContentType);
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASblob.FetchAttributes(),
                    "Fetch blob attributes while SAS does not allow for reading",
                    failureCode);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                SASblob.SetMetadata();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASblob.SetMetadata(),
                    "Set blob metadata while SAS does not allow for writing",
                    failureCode);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                SASblob.Delete();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASblob.Delete(),
                    "Delete blob while SAS does not allow for deleting",
                    failureCode);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="SharedAccessBlobHeaders"/> class based on an existing instance.
        /// </summary>
        /// <param name="sharedAccessBlobHeaders">The set of <see cref="SharedAccessBlobHeaders"/> to clone.</param>
        public SharedAccessBlobHeaders(SharedAccessBlobHeaders sharedAccessBlobHeaders)
        {
            CommonUtility.AssertNotNull("sharedAccessBlobHeaders", sharedAccessBlobHeaders);

            this.ContentType = sharedAccessBlobHeaders.ContentType;
            this.ContentDisposition = sharedAccessBlobHeaders.ContentDisposition;
            this.ContentEncoding = sharedAccessBlobHeaders.ContentEncoding;
            this.ContentLanguage = sharedAccessBlobHeaders.ContentLanguage;
            this.CacheControl = sharedAccessBlobHeaders.CacheControl;
        }
        /// <summary>
        /// Get the complete query builder for creating the Shared Access Signature query.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a blob returned with this SAS.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceType">Either "b" for blobs or "c" for containers.</param>
        /// <param name="signature">The signature to use.</param>
        /// <param name="accountKeyName">The name of the key used to create the signature, or <c>null</c> if the key is implicit.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <returns>The finished query builder.</returns>
        internal static UriQueryBuilder GetSignature(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceType,
            string signature,
            string accountKeyName,
            string sasVersion,
            SharedAccessProtocol? protocols,
            IPAddressOrRange ipAddressOrRange
            )
        {
            CommonUtility.AssertNotNullOrEmpty("resourceType", resourceType);

            UriQueryBuilder builder = new UriQueryBuilder();

            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedVersion, sasVersion);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedResource, resourceType);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIdentifier, accessPolicyIdentifier);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedKey, accountKeyName);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.Signature, signature);
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedProtocols, GetProtocolString(protocols));
            AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedIP, ipAddressOrRange == null ? null : ipAddressOrRange.ToString());

            if (policy != null)
            {
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedStart, GetDateTimeOrNull(policy.SharedAccessStartTime));
                AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedExpiry, GetDateTimeOrNull(policy.SharedAccessExpiryTime));

                string permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                if (!string.IsNullOrEmpty(permissions))
                {
                    AddEscapedIfNotNull(builder, Constants.QueryConstants.SignedPermissions, permissions);
                }
            }

            if (headers != null)
            {
                AddEscapedIfNotNull(builder, Constants.QueryConstants.CacheControl, headers.CacheControl);
                AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentType, headers.ContentType);
                AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentEncoding, headers.ContentEncoding);
                AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentLanguage, headers.ContentLanguage);
                AddEscapedIfNotNull(builder, Constants.QueryConstants.ContentDisposition, headers.ContentDisposition);
            }

            return builder;
        }
Exemplo n.º 4
0
 /// <summary>
 /// Returns a shared access signature for the blob.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
 /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier)
 {
     return(this.GetSharedAccessSignature(policy, headers, groupPolicyIdentifier, null, null));
 }
Exemplo n.º 5
0
        public void CloudAppendBlobSASHeaders()
        {
            for (int i = 1; i < 0x40; i++)
            {
                CloudAppendBlob testBlob = this.testContainer.GetAppendBlobReference("blob" + i);
                SharedAccessBlobPermissions permissions = (SharedAccessBlobPermissions)i;
                SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders()
                {
                    CacheControl = "no-transform",
                    ContentDisposition = "attachment",
                    ContentEncoding = "gzip",
                    ContentLanguage = "tr,en",
                    ContentType = "text/html"
                };

                TestBlobSAS(testBlob, permissions, headers);
            }
        }
Exemplo n.º 6
0
        private static async Task TestAccessAsync(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob)
        {
            OperationContext operationContext = new OperationContext();
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                new StorageCredentials() :
                new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(container.Uri, credentials);
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = container.GetBlockBlobReference(blob.Name);
                }
                else
                {
                    blob = container.GetPageBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = new CloudBlockBlob(blob.Uri, credentials);
                }
                else
                {
                    blob = new CloudPageBlob(blob.Uri, credentials);
                }
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    await container.ListBlobsSegmentedAsync(null);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync(
                        async () => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.None, null, null, null, operationContext),
                        operationContext,
                        "List blobs while SAS does not allow for listing",
                        HttpStatusCode.Forbidden);
                }
            }

            if ((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read)
            {
                await blob.FetchAttributesAsync();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, blob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, blob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, blob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, blob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, blob.Properties.ContentType);
                    }
                }
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async () => await blob.FetchAttributesAsync(null, null, operationContext),
                    operationContext,
                    "Fetch blob attributes while SAS does not allow for reading",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                await blob.SetMetadataAsync();
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async () => await blob.SetMetadataAsync(null, null, operationContext),
                    operationContext,
                    "Set blob metadata while SAS does not allow for writing",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                await blob.DeleteAsync();
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async () => await blob.DeleteAsync(DeleteSnapshotsOption.None, null, null, operationContext),
                    operationContext,
                    "Delete blob while SAS does not allow for deleting",
                    HttpStatusCode.Forbidden);
            }
        }
Exemplo n.º 7
0
        private static async Task TestBlobSASAsync(CloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers)
        {
            await UploadTextAsync(testBlob, "blob", Encoding.UTF8);

            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions = permissions,
            };

            string sasToken = testBlob.GetSharedAccessSignature(policy, headers);
            await TestAccessAsync(sasToken, permissions, headers, null, testBlob);
        }
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new NotImplementedException();
 }
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 10
0
        public void CloudPageBlobHeaders20120212SASVersion()
        {
            SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders()
            {
                CacheControl = "no-transform",
                ContentDisposition = "attachment",
                ContentEncoding = "gzip",
                ContentLanguage = "tr,en",
                ContentType = "text/html"
            };

            try
            {
                CloudPageBlob testBlob = this.testContainer.GetPageBlobReference("blob" + 1);
                SharedAccessBlobPermissions permissions = (SharedAccessBlobPermissions)1;
                TestBlobSAS(testBlob, permissions, headers, Constants.VersionConstants.February2012);
                Assert.Fail();
            }
            catch (ArgumentException e)
            {
                Assert.AreEqual(SR.InvalidHeaders, e.Message);
            }
        }
Exemplo n.º 11
0
        private static async Task TestBlobSASAsync(CloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers)
        {
            await UploadTextAsync(testBlob, "blob", Encoding.UTF8);

            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions            = permissions,
            };

            string sasToken = testBlob.GetSharedAccessSignature(policy, headers);

            await TestAccessAsync(sasToken, permissions, headers, null, testBlob);
        }
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.InvariantCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            string resourceName = this.GetCanonicalName(true /* ignoreSnapshotTime */, Constants.HeaderConstants.TargetStorageVersion);
            StorageAccountKey accountKey = this.ServiceClient.Credentials.Key;
            string signature = SharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, Constants.HeaderConstants.TargetStorageVersion, accountKey.KeyValue);

            // Future resource type changes from "c" => "container"
            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, "b", signature, accountKey.KeyName, Constants.HeaderConstants.TargetStorageVersion);

            return builder.ToString();
        }
 /// <summary>
 /// Returns a shared access signature for the blob.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers)
 {
     return this.GetSharedAccessSignature(policy, headers, null /* groupPolicyIdentifier */);
 }
Exemplo n.º 14
0
        private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob)
        {
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                                             new StorageCredentials() :
                                             new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(credentials.TransformUri(container.Uri));
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = container.GetBlockBlobReference(blob.Name);
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    blob = container.GetPageBlobReference(blob.Name);
                }
                else
                {
                    blob = container.GetAppendBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = new CloudBlockBlob(credentials.TransformUri(blob.Uri));
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    blob = new CloudPageBlob(credentials.TransformUri(blob.Uri));
                }
                else
                {
                    blob = new CloudAppendBlob(credentials.TransformUri(blob.Uri));
                }
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    container.ListBlobs().ToArray();
                }
                else
                {
                    TestHelper.ExpectedException(
                        () => container.ListBlobs().ToArray(),
                        "List blobs while SAS does not allow for listing",
                        HttpStatusCode.NotFound);
                }
            }

            if ((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read)
            {
                blob.FetchAttributes();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, blob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, blob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, blob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, blob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, blob.Properties.ContentType);
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => blob.FetchAttributes(),
                    "Fetch blob attributes while SAS does not allow for reading",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                blob.SetMetadata();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => blob.SetMetadata(),
                    "Set blob metadata while SAS does not allow for writing",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                blob.Delete();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => blob.Delete(),
                    "Delete blob while SAS does not allow for deleting",
                    HttpStatusCode.NotFound);
            }
        }
Exemplo n.º 15
0
        private static void TestBlobSAS(CloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, string sasVersion)
        {
            UploadText(testBlob, "blob", Encoding.UTF8);

            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime  = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions            = permissions,
            };

            string sasToken = testBlob.GetSharedAccessSignature(policy, headers, null, sasVersion);

            TestAccess(sasToken, permissions, headers, null, testBlob);
        }
Exemplo n.º 16
0
#pragma warning disable 0618
        private static void TestBlobSAS(CloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers)
        {
            TestBlobSAS(testBlob, permissions, headers, null);
        }
Exemplo n.º 17
0
        private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob)
        {
            CloudBlob          SASblob;
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                                             new StorageCredentials() :
                                             new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(credentials.TransformUri(container.Uri));
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    SASblob = container.GetBlockBlobReference(blob.Name);
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    SASblob = container.GetPageBlobReference(blob.Name);
                }
                else
                {
                    SASblob = container.GetAppendBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    SASblob = new CloudBlockBlob(credentials.TransformUri(blob.Uri));
                }
                else if (blob.BlobType == BlobType.PageBlob)
                {
                    SASblob = new CloudPageBlob(credentials.TransformUri(blob.Uri));
                }
                else
                {
                    SASblob = new CloudAppendBlob(credentials.TransformUri(blob.Uri));
                }
            }

            // We want to ensure that 'create', 'add', and 'write' permissions all allow for correct writing of blobs, as is reasonable.
            if (((permissions & SharedAccessBlobPermissions.Create) == SharedAccessBlobPermissions.Create) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
            {
                if (blob.BlobType == BlobType.PageBlob)
                {
                    CloudPageBlob SASpageBlob = (CloudPageBlob)SASblob;
                    SASpageBlob.Create(512);
                    CloudPageBlob pageBlob = (CloudPageBlob)blob;
                    byte[]        buffer   = new byte[512];
                    buffer[0] = 2;  // random data

                    if (((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
                    {
                        SASpageBlob.UploadFromByteArray(buffer, 0, 512);
                    }
                    else
                    {
                        TestHelper.ExpectedException(
                            () => SASpageBlob.UploadFromByteArray(buffer, 0, 512),
                            "pageBlob SAS token without Write perms should not allow for writing/adding",
                            HttpStatusCode.Forbidden);
                        pageBlob.UploadFromByteArray(buffer, 0, 512);
                    }
                }
                else if (blob.BlobType == BlobType.BlockBlob)
                {
                    if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
                    {
                        UploadText(SASblob, "blob", Encoding.UTF8);
                    }
                    else
                    {
                        TestHelper.ExpectedException(
                            () => UploadText(SASblob, "blob", Encoding.UTF8),
                            "Block blob SAS token without Write or perms should not allow for writing",
                            HttpStatusCode.Forbidden);
                        UploadText(blob, "blob", Encoding.UTF8);
                    }
                }
                else // append blob
                {
                    // If the sas token contains Feb 2012, append won't be accepted
                    if (sasToken.Contains(Constants.VersionConstants.February2012))
                    {
                        UploadText(blob, "blob", Encoding.UTF8);
                    }
                    else
                    {
                        CloudAppendBlob SASAppendBlob = SASblob as CloudAppendBlob;
                        SASAppendBlob.CreateOrReplace();

                        byte[] textAsBytes = Encoding.UTF8.GetBytes("blob");
                        using (MemoryStream stream = new MemoryStream())
                        {
                            stream.Write(textAsBytes, 0, textAsBytes.Length);
                            stream.Seek(0, SeekOrigin.Begin);

                            if (((permissions & SharedAccessBlobPermissions.Add) == SharedAccessBlobPermissions.Add) || ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write))
                            {
                                SASAppendBlob.AppendBlock(stream, null);
                            }
                            else
                            {
                                TestHelper.ExpectedException(
                                    () => SASAppendBlob.AppendBlock(stream, null),
                                    "Append blob SAS token without Write or Add perms should not allow for writing/adding",
                                    HttpStatusCode.Forbidden);
                                stream.Seek(0, SeekOrigin.Begin);
                                ((CloudAppendBlob)blob).AppendBlock(stream, null);
                            }
                        }
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => UploadText(SASblob, "blob", Encoding.UTF8),
                    "UploadText SAS does not allow for writing/adding",
                    ((blob.BlobType == BlobType.AppendBlob) && (sasToken != null) && (sasToken.Contains(Constants.VersionConstants.February2012))) ? HttpStatusCode.BadRequest : HttpStatusCode.Forbidden);
                UploadText(blob, "blob", Encoding.UTF8);
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    container.ListBlobs().ToArray();
                }
                else
                {
                    TestHelper.ExpectedException(
                        () => container.ListBlobs().ToArray(),
                        "List blobs while SAS does not allow for listing",
                        HttpStatusCode.Forbidden);
                }
            }

            // need to have written to the blob to read from it.
            if (((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read))
            {
                SASblob.FetchAttributes();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, SASblob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, SASblob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, SASblob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, SASblob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, SASblob.Properties.ContentType);
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASblob.FetchAttributes(),
                    "Fetch blob attributes while SAS does not allow for reading",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                SASblob.SetMetadata();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASblob.SetMetadata(),
                    "Set blob metadata while SAS does not allow for writing",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                SASblob.Delete();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => SASblob.Delete(),
                    "Delete blob while SAS does not allow for deleting",
                    HttpStatusCode.Forbidden);
            }
        }
Exemplo n.º 18
0
 private static void TestBlobSAS(ICloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers)
 {
     TestBlobSAS(testBlob, permissions, headers, null);
 }
Exemplo n.º 19
0
        private static void TestBlobSAS(ICloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, string sasVersion)
        {
            UploadText(testBlob, "blob", Encoding.UTF8);

            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions = permissions,
            };

            string sasToken = testBlob.GetSharedAccessSignature(policy, headers, null, sasVersion);
            TestAccess(sasToken, permissions, headers, null, testBlob);
        }
Exemplo n.º 20
0
        private static async Task TestAccessAsync(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, CloudBlob blob, HttpStatusCode setBlobMetadataWhileSasExpectedStatusCode = HttpStatusCode.Forbidden, HttpStatusCode deleteBlobWhileSasExpectedStatusCode = HttpStatusCode.Forbidden, HttpStatusCode listBlobWhileSasExpectedStatusCode = HttpStatusCode.Forbidden)
        {
            OperationContext   operationContext = new OperationContext();
            StorageCredentials credentials      = string.IsNullOrEmpty(sasToken) ?
                                                  new StorageCredentials() :
                                                  new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(container.Uri, credentials);
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = container.GetBlockBlobReference(blob.Name);
                }
                else
                {
                    blob = container.GetPageBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = new CloudBlockBlob(blob.Uri, credentials);
                }
                else
                {
#if !FACADE_NETCORE
                    blob = new CloudPageBlob(blob.Uri, credentials);
#else
                    blob = new CloudPageBlob(blob.Uri, null, credentials);
#endif
                }
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    await container.ListBlobsSegmentedAsync(null);
                }
                else
                {
                    await TestHelper.ExpectedExceptionAsync(
                        async() => await container.ListBlobsSegmentedAsync(null, true, BlobListingDetails.None, null, null, null, operationContext),
                        operationContext,
                        "List blobs while SAS does not allow for listing",
                        listBlobWhileSasExpectedStatusCode);
                }
            }

            if ((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read)
            {
                await blob.FetchAttributesAsync();

                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, blob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, blob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, blob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, blob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, blob.Properties.ContentType);
                    }
                }
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.FetchAttributesAsync(null, null, operationContext),
                    operationContext,
                    "Fetch blob attributes while SAS does not allow for reading",
                    HttpStatusCode.Forbidden);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                await blob.SetMetadataAsync();
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.SetMetadataAsync(null, null, operationContext),
                    operationContext,
                    "Set blob metadata while SAS does not allow for writing",
                    setBlobMetadataWhileSasExpectedStatusCode);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                await blob.DeleteAsync();
            }
            else
            {
                await TestHelper.ExpectedExceptionAsync(
                    async() => await blob.DeleteAsync(DeleteSnapshotsOption.None, null, null, operationContext),
                    operationContext,
                    "Delete blob while SAS does not allow for deleting",
                    deleteBlobWhileSasExpectedStatusCode);
            }
        }
Exemplo n.º 21
0
        private static void TestAccess(string sasToken, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers, CloudBlobContainer container, ICloudBlob blob)
        {
            StorageCredentials credentials = string.IsNullOrEmpty(sasToken) ?
                new StorageCredentials() :
                new StorageCredentials(sasToken);

            if (container != null)
            {
                container = new CloudBlobContainer(credentials.TransformUri(container.Uri));
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = container.GetBlockBlobReference(blob.Name);
                }
                else
                {
                    blob = container.GetPageBlobReference(blob.Name);
                }
            }
            else
            {
                if (blob.BlobType == BlobType.BlockBlob)
                {
                    blob = new CloudBlockBlob(credentials.TransformUri(blob.Uri));
                }
                else
                {
                    blob = new CloudPageBlob(credentials.TransformUri(blob.Uri));
                }
            }

            if (container != null)
            {
                if ((permissions & SharedAccessBlobPermissions.List) == SharedAccessBlobPermissions.List)
                {
                    container.ListBlobs().ToArray();
                }
                else
                {
                    TestHelper.ExpectedException(
                        () => container.ListBlobs().ToArray(),
                        "List blobs while SAS does not allow for listing",
                        HttpStatusCode.NotFound);
                }
            }

            if ((permissions & SharedAccessBlobPermissions.Read) == SharedAccessBlobPermissions.Read)
            {
                blob.FetchAttributes();
                
                // Test headers
                if (headers != null)
                {
                    if (headers.CacheControl != null)
                    {
                        Assert.AreEqual(headers.CacheControl, blob.Properties.CacheControl);
                    }

                    if (headers.ContentDisposition != null)
                    {
                        Assert.AreEqual(headers.ContentDisposition, blob.Properties.ContentDisposition);
                    }

                    if (headers.ContentEncoding != null)
                    {
                        Assert.AreEqual(headers.ContentEncoding, blob.Properties.ContentEncoding);
                    }

                    if (headers.ContentLanguage != null)
                    {
                        Assert.AreEqual(headers.ContentLanguage, blob.Properties.ContentLanguage);
                    }

                    if (headers.ContentType != null)
                    {
                        Assert.AreEqual(headers.ContentType, blob.Properties.ContentType);
                    }
                }
            }
            else
            {
                TestHelper.ExpectedException(
                    () => blob.FetchAttributes(),
                    "Fetch blob attributes while SAS does not allow for reading",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessBlobPermissions.Write) == SharedAccessBlobPermissions.Write)
            {
                blob.SetMetadata();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => blob.SetMetadata(),
                    "Set blob metadata while SAS does not allow for writing",
                    HttpStatusCode.NotFound);
            }

            if ((permissions & SharedAccessBlobPermissions.Delete) == SharedAccessBlobPermissions.Delete)
            {
                blob.Delete();
            }
            else
            {
                TestHelper.ExpectedException(
                    () => blob.Delete(),
                    "Delete blob while SAS does not allow for deleting",
                    HttpStatusCode.NotFound);
            }
        }
Exemplo n.º 22
0
 /// <summary>
 /// Returns a shared access signature for the blob.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
 /// <returns>A shared access signature.</returns>
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers)
 {
     return(this.GetSharedAccessSignature(policy, headers, null /* groupPolicyIdentifier */, null /* sasVersion */));
 }
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, string sasVersion)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Get the signature hash embedded inside the Shared Access Signature.
        /// </summary>
        /// <param name="policy">The shared access policy to hash.</param>
        /// <param name="headers">The optional header values to set for a blob returned with this SAS.</param>
        /// <param name="accessPolicyIdentifier">An optional identifier for the policy.</param>
        /// <param name="resourceName">The canonical resource string, unescaped.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format.</param>
        /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param>
        /// <param name="ipAddressOrRange">The IP range for IPSAS.</param>
        /// <param name="keyValue">The key value retrieved as an atomic operation used for signing.</param>
        /// <returns>The signed hash.</returns>
        internal static string GetHash(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            SharedAccessProtocol? protocols,
            IPAddressOrRange ipAddressOrRange,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string permissions = null;
            DateTimeOffset? startTime = null;
            DateTimeOffset? expiryTime = null;
            if (policy != null)
            {
                permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                startTime = policy.SharedAccessStartTime;
                expiryTime = policy.SharedAccessExpiryTime;
            }

            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedIP + "\n" + 
            ////                     signedProtocol + "\n" + 
            ////                     signedversion + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype 
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////

            string cacheControl = null;
            string contentDisposition = null;
            string contentEncoding = null;
            string contentLanguage = null;
            string contentType = null;
            if (headers != null)
            {
                cacheControl = headers.CacheControl;
                contentDisposition = headers.ContentDisposition;
                contentEncoding = headers.ContentEncoding;
                contentLanguage = headers.ContentLanguage;
                contentType = headers.ContentType;
            }

            string stringToSign = string.Format(
                                    CultureInfo.InvariantCulture,
                                    "{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}\n{11}\n{12}",
                                    permissions,
                                    GetDateTimeOrEmpty(startTime),
                                    GetDateTimeOrEmpty(expiryTime),
                                    resourceName,
                                    accessPolicyIdentifier,
                                    ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(),
                                    GetProtocolString(protocols),
                                    sasVersion,
                                    cacheControl,
                                    contentDisposition,
                                    contentEncoding,
                                    contentLanguage,
                                    contentType);

            Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign);

            return CryptoUtility.ComputeHmac256(keyValue, stringToSign);
        }
        public string GetBlobSasUrl(string containerName, string blobName, DateTimeOffset expiry, bool isDownload = false, 
            string filename = null, string contentType = null, BlobUrlAccess access = BlobUrlAccess.Read)
        {
            var blob = _blobClient.GetContainerReference(containerName)
                .GetBlockBlobReference(blobName);

            var builder = new UriBuilder(blob.Uri);
            var headers = new SharedAccessBlobHeaders();
            var hasFilename = !string.IsNullOrEmpty(filename);

            if (hasFilename || isDownload)
            {
                headers.ContentDisposition = "attachment" + (hasFilename ? "; filename=\"" + filename + "\"" : string.Empty);
            }

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

            builder.Query = blob.GetSharedAccessSignature(new SharedAccessBlobPolicy
            {
                Permissions = access.ToPermissions(),
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = expiry,
            }, headers).TrimStart('?');

            return builder.Uri.ToString();
        }
 /// <summary>
 /// Returns a shared access signature for the blob.
 /// </summary>
 /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
 /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
 /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
 /// <returns>A shared access signature, as a URI query string.</returns>
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier)
 {
     return this.GetSharedAccessSignature(policy, headers, groupPolicyIdentifier, null /* sasVersion */);
 }
Exemplo n.º 27
0
        public async Task CloudPageBlobSASHeadersAsync()
        {
            for (int i = 1; i < 8; i++)
            {
                CloudPageBlob testBlob = this.testContainer.GetPageBlobReference("blob" + i);
                SharedAccessBlobPermissions permissions = (SharedAccessBlobPermissions)i;
                SharedAccessBlobHeaders headers = new SharedAccessBlobHeaders()
                {
                    CacheControl = "no-transform",
                    ContentDisposition = "attachment",
#if !ASPNET_K
                    ContentEncoding = "gzip",
#endif
                    ContentLanguage = "tr,en",
                    ContentType = "text/html"
                };

                await TestBlobSASAsync(testBlob, permissions, headers);
            }
        }
Exemplo n.º 28
0
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier)
 {
     throw new System.NotImplementedException();
 }
Exemplo n.º 29
0
        private static void TestBlobSAS(CloudBlob testBlob, SharedAccessBlobPermissions permissions, SharedAccessBlobHeaders headers)
        {
            SharedAccessBlobPolicy policy = new SharedAccessBlobPolicy()
            {
                SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5),
                SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddMinutes(30),
                Permissions = permissions,
            };

            string sasToken = testBlob.GetSharedAccessSignature(policy, headers, null);
            TestAccess(sasToken, permissions, headers, null, testBlob);
        }
        internal static string GetHash(
            SharedAccessBlobPolicy policy,
            SharedAccessBlobHeaders headers,
            string accessPolicyIdentifier,
            string resourceName,
            string sasVersion,
            byte[] keyValue)
        {
            CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName);
            CommonUtility.AssertNotNull("keyValue", keyValue);
            CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion);

            string permissions = null;
            DateTimeOffset? startTime = null;
            DateTimeOffset? expiryTime = null;
            if (policy != null)
            {
                permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions);
                startTime = policy.SharedAccessStartTime;
                expiryTime = policy.SharedAccessExpiryTime;
            }
            
            //// StringToSign =      signedpermissions + "\n" +
            ////                     signedstart + "\n" +
            ////                     signedexpiry + "\n" +
            ////                     canonicalizedresource + "\n" +
            ////                     signedidentifier + "\n" +
            ////                     signedversion + "\n" +
            ////                     cachecontrol + "\n" +
            ////                     contentdisposition + "\n" +
            ////                     contentencoding + "\n" +
            ////                     contentlanguage + "\n" +
            ////                     contenttype 
            ////
            //// HMAC-SHA256(UTF8.Encode(StringToSign))
            ////
            //// Note that the final five headers are invalid for the 2012-02-12 version.

            string stringToSign = string.Format(
                                    CultureInfo.InvariantCulture,
                                    "{0}\n{1}\n{2}\n{3}\n{4}\n{5}",
                                    permissions,
                                    GetDateTimeOrEmpty(startTime),
                                    GetDateTimeOrEmpty(expiryTime),
                                    resourceName,
                                    accessPolicyIdentifier,
                                    sasVersion);

            if (string.Equals(sasVersion, Constants.VersionConstants.February2012))
            {
                if (headers != null)
                {
                    string errorString = string.Format(CultureInfo.CurrentCulture, SR.InvalidHeaders);
                    throw new ArgumentException(errorString);
                }
            }
            else
            {
                string cacheControl = null;
                string contentDisposition = null;
                string contentEncoding = null;
                string contentLanguage = null;
                string contentType = null;
                if (headers != null)
                {
                    cacheControl = headers.CacheControl;
                    contentDisposition = headers.ContentDisposition;
                    contentEncoding = headers.ContentEncoding;
                    contentLanguage = headers.ContentLanguage;
                    contentType = headers.ContentType;
                }

                stringToSign = stringToSign + string.Format(
                                                CultureInfo.InvariantCulture,
                                                "\n{0}\n{1}\n{2}\n{3}\n{4}",
                                                cacheControl,
                                                contentDisposition,
                                                contentEncoding,
                                                contentLanguage,
                                                contentType);
            }

            return CryptoUtility.ComputeHmac256(keyValue, stringToSign);
        }
        /// <summary>
        /// Returns a shared access signature for the blob.
        /// </summary>
        /// <param name="policy">A <see cref="SharedAccessBlobPolicy"/> object specifying the access policy for the shared access signature.</param>
        /// <param name="headers">A <see cref="SharedAccessBlobHeaders"/> object specifying optional header values to set for a blob accessed with this SAS.</param>
        /// <param name="groupPolicyIdentifier">A string identifying a stored access policy.</param>
        /// <param name="sasVersion">A string indicating the desired SAS version to use, in storage service version format. Value must be <c>2012-02-12</c> or later.</param>
        /// <returns>A shared access signature, as a URI query string.</returns>
        public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, string sasVersion)
        {
            if (!this.ServiceClient.Credentials.IsSharedKey)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASWithoutAccountKey);
                throw new InvalidOperationException(errorMessage);
            }

            if (this.SnapshotTime != null)
            {
                string errorMessage = string.Format(CultureInfo.CurrentCulture, SR.CannotCreateSASForSnapshot);
                throw new NotSupportedException(errorMessage);
            }

            string resourceName = this.GetCanonicalName(true);
            StorageAccountKey accountKey = this.ServiceClient.Credentials.Key;
            string validatedSASVersion = SharedAccessSignatureHelper.ValidateSASVersionString(sasVersion);
            string signature = SharedAccessSignatureHelper.GetHash(policy, headers, groupPolicyIdentifier, resourceName, validatedSASVersion, accountKey.KeyValue);

            // Future resource type changes from "c" => "container"
            UriQueryBuilder builder = SharedAccessSignatureHelper.GetSignature(policy, headers, groupPolicyIdentifier, "b", signature, accountKey.KeyName, validatedSASVersion);

            return builder.ToString();
        }
Exemplo n.º 32
0
 public string GetSharedAccessSignature(SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string groupPolicyIdentifier, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange)
 {
     throw new System.NotImplementedException();
 }