Beispiel #1
0
        /// <summary>
        /// Update the access policy
        /// </summary>
        /// <param name="policy">Access policy object</param>
        /// <param name="shouldSetExpiryTime">Should set the default expiry time</param>
        private void SetupAccessPolicy(SharedAccessBlobPolicy policy, bool shouldSetExpiryTime)
        {
            DateTimeOffset?accessStartTime;
            DateTimeOffset?accessEndTime;

            SasTokenHelper.SetupAccessPolicyLifeTime(StartTime, ExpiryTime,
                                                     out accessStartTime, out accessEndTime, shouldSetExpiryTime);
            policy.SharedAccessStartTime  = accessStartTime;
            policy.SharedAccessExpiryTime = accessEndTime;
            AccessPolicyHelper.SetupAccessPolicyPermission(policy, Permission);
        }
        static string GetDeviceToken(string iothubHostName, string deviceId, string moduleId, string key)
        {
            DateTime startTime = DateTime.UtcNow;
            string   audience  = WebUtility.UrlEncode($"{iothubHostName}/devices/{deviceId}/modules/{moduleId}");
            string   expiresOn = SasTokenHelper.BuildExpiresOn(startTime, TimeSpan.FromHours(1));
            string   data      = string.Join("\n", new List <string> {
                audience, expiresOn
            });
            string signature = Sign(data, key);

            return(SasTokenHelper.BuildSasToken(audience, signature, expiresOn));
        }
Beispiel #3
0
        public void BuildExpiresOnTest()
        {
            // Arrange
            var      startTime = new DateTime(2019, 01, 01);
            TimeSpan ttl       = TimeSpan.FromHours(1);

            // Act
            string expiresOn = SasTokenHelper.BuildExpiresOn(startTime, ttl);

            // Assert
            Assert.Equal("1546304400", expiresOn);
        }
        public void SetupAccessPolicyLifeTimeTest()
        {
            DateTime?      start     = DateTime.Now;
            DateTime?      end       = start.Value.AddHours(1.0);
            DateTimeOffset?testStart = null;
            DateTimeOffset?testEnd   = null;

            SasTokenHelper.SetupAccessPolicyLifeTime(start, end, out testStart, out testEnd, true);
            Assert.AreEqual(testStart.Value.UtcDateTime.ToString(), start.Value.ToUniversalTime().ToString());
            Assert.AreEqual(testEnd.Value.UtcDateTime.ToString(), end.Value.ToUniversalTime().ToString());
            AssertThrows <ArgumentException>(() => SasTokenHelper.SetupAccessPolicyLifeTime(end, start, out testStart, out testEnd, true));
        }
        public void BuildAudienceDeviceTest()
        {
            // Arrange
            string iotHubHostName = "testIotHub.azure-devices.net";
            string deviceId       = "device1";

            // Act
            string audience = SasTokenHelper.BuildAudience(iotHubHostName, deviceId);

            // Assert
            Assert.Equal("testIotHub.azure-devices.net%2Fdevices%2Fdevice1", audience);
        }
Beispiel #6
0
        public void BuildAudienceDevice_WithSplChars_Test()
        {
            // Arrange
            string iotHubHostName = "testIotHub.azure-devices.net";
            string deviceId       = "[email protected]#st";

            // Act
            string audience = SasTokenHelper.BuildAudience(iotHubHostName, deviceId);

            // Assert
            Assert.Equal("testIotHub.azure-devices.net%2Fdevices%2Fn%2540m.et%2523st", audience);
        }
Beispiel #7
0
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name))
            {
                return;
            }

            // When the input context is Oauth bases, can't generate normal SAS, but UserDelegationSas
            bool generateUserDelegationSas = false;

            if (Channel != null && Channel.StorageContext != null && Channel.StorageContext.StorageAccount.Credentials.IsToken)
            {
                if (ShouldProcess(Name, "Generate User Delegation SAS, since input Storage Context is OAuth based."))
                {
                    generateUserDelegationSas = true;
                    if (!string.IsNullOrEmpty(accessPolicyIdentifier))
                    {
                        throw new ArgumentException("When input Storage Context is OAuth based, Saved Policy is not supported.", "Policy");
                    }
                }
                else
                {
                    return;
                }
            }

            CloudBlobContainer     container    = Channel.GetContainerReference(Name);
            SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
            bool shouldSetExpiryTime            = SasTokenHelper.ValidateContainerAccessPolicy(Channel, container.Name, accessPolicy, accessPolicyIdentifier);

            SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
            string sasToken;

            if (generateUserDelegationSas)
            {
                UserDelegationKey userDelegationKey = Channel.GetUserDelegationKey(accessPolicy.SharedAccessStartTime, accessPolicy.SharedAccessExpiryTime, null, null, OperationContext);
                sasToken = container.GetUserDelegationSharedAccessSignature(userDelegationKey, accessPolicy, null, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));
            }
            else
            {
                sasToken = container.GetSharedAccessSignature(accessPolicy, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));
            }

            if (FullUri)
            {
                string fullUri = SasTokenHelper.GetFullUriWithSASToken(container.Uri.AbsoluteUri.ToString(), sasToken);
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
        public void ValidateExistingPolicyTest()
        {
            Dictionary <string, string> policies = new Dictionary <string, string>()
            {
                { "test", "test" }, { "Abc", "abc" }, { "123", "123" }
            };

            SasTokenHelper.GetExistingPolicy <string>(policies, "ABC");
            SasTokenHelper.GetExistingPolicy <string>(policies, "test");
            SasTokenHelper.GetExistingPolicy <string>(policies, "tesT");
            SasTokenHelper.GetExistingPolicy <string>(policies, "123");
            AssertThrows <ArgumentException>(() => SasTokenHelper.GetExistingPolicy <string>(policies, "test1"));
        }
Beispiel #9
0
        public void BuildSasTokenTest()
        {
            // Arrange
            string audience      = "testIotHub.azure-devices.net%2Fdevices%2Fdevice1%2Fmodules%2Fmodule1";
            string signature     = Guid.NewGuid().ToString();
            string expiry        = "1546304400";
            string expectedToken = $"SharedAccessSignature sr=testIotHub.azure-devices.net%2Fdevices%2Fdevice1%2Fmodules%2Fmodule1&sig={signature}&se=1546304400";

            // Act
            string sasToken = SasTokenHelper.BuildSasToken(audience, signature, expiry);

            // Assert
            Assert.Equal(expectedToken, sasToken);
        }
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(ShareName))
            {
                return;
            }

            CloudFileShare fileShare = null;
            CloudFile      file      = null;

            if (null != this.File)
            {
                file      = this.File;
                fileShare = this.File.Share;
            }
            else
            {
                string[] path = NamingUtil.ValidatePath(this.Path, true);
                fileShare = Channel.GetShareReference(this.ShareName);
                file      = fileShare.GetRootDirectoryReference().GetFileReferenceByPath(path);
            }

            SharedAccessFilePolicy accessPolicy = new SharedAccessFilePolicy();

            bool shouldSetExpiryTime = SasTokenHelper.ValidateShareAccessPolicy(
                Channel,
                fileShare.Name,
                accessPolicyIdentifier,
                !string.IsNullOrEmpty(this.Permission),
                this.StartTime.HasValue,
                this.ExpiryTime.HasValue);

            SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);

            string sasToken = file.GetSharedAccessSignature(accessPolicy, null, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));

            if (FullUri)
            {
                string fullUri = SasTokenHelper.GetFullUriWithSASToken(file.SnapshotQualifiedUri.AbsoluteUri.ToString(), sasToken);

                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
        public async Task SignTest()
        {
            // Arrange
            string audience  = SasTokenHelper.BuildAudience("foo.azure-devices.net", "ed1", "$edgeHub");
            string expiresOn = SasTokenHelper.BuildExpiresOn(new DateTime(2018, 01, 01), TimeSpan.FromHours(1));
            string data      = string.Join("\n", new List <string> {
                audience, expiresOn
            });
            string key               = Convert.ToBase64String(Encoding.UTF8.GetBytes("DummyKey123"));
            string expectedToken     = Convert.ToBase64String(new HMACSHA256(Convert.FromBase64String(key)).ComputeHash(Encoding.UTF8.GetBytes(data)));
            var    signatureProvider = new SharedAccessKeySignatureProvider(key);

            // Act
            string token = await signatureProvider.SignAsync(data);

            // Assert
            Assert.Equal(expectedToken, token);
        }
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name)) return;
            CloudBlobContainer container = Channel.GetContainerReference(Name);
            SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
            bool shouldSetExpiryTime = SasTokenHelper.ValidateContainerAccessPolicy(Channel, container.Name, accessPolicy, accessPolicyIdentifier);
            SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
            string sasToken = container.GetSharedAccessSignature(accessPolicy, accessPolicyIdentifier);

            if (FullUri)
            {
                string fullUri = SasTokenHelper.GetFullUriWithSASToken(container.Uri.AbsoluteUri.ToString(), sasToken);
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
        public override void ExecuteCmdlet()
        {
            var sharedAccessPolicy = new SharedAccessAccountPolicy()
            {
                Permissions      = SetupAccessPolicyPermission(this.Permission),
                Services         = Service,
                ResourceTypes    = ResourceType,
                Protocols        = Protocol,
                IPAddressOrRange = Util.SetupIPAddressOrRangeForSAS(this.IPAddressOrRange)
            };

            DateTimeOffset?accessStartTime;
            DateTimeOffset?accessEndTime;

            SasTokenHelper.SetupAccessPolicyLifeTime(StartTime, ExpiryTime,
                                                     out accessStartTime, out accessEndTime, true);
            sharedAccessPolicy.SharedAccessStartTime  = accessStartTime;
            sharedAccessPolicy.SharedAccessExpiryTime = accessEndTime;

            this.WriteObject(Channel.GetStorageAccountSASToken(sharedAccessPolicy));
        }
Beispiel #14
0
        public override void ExecuteCmdlet()
        {
            CloudBlob blob = null;

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

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

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

            if (FullUri)
            {
                string fullUri = blob.SnapshotQualifiedUri.ToString();
                if (blob.IsSnapshot)
                {
                    // Since snapshot URL already has '?', need remove '?' in the first char of sas
                    fullUri = fullUri + "&" + sasToken.Substring(1);
                }
                else
                {
                    fullUri = fullUri + sasToken;
                }
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name))
            {
                return;
            }
            CloudQueue queue = Channel.GetQueueReference(Name);
            SharedAccessQueuePolicy policy = new SharedAccessQueuePolicy();
            bool shouldSetExpiryTime       = SasTokenHelper.ValidateQueueAccessPolicy(Channel, queue.Name, policy, accessPolicyIdentifier);

            SetupAccessPolicy(policy, shouldSetExpiryTime);
            string sasToken = queue.GetSharedAccessSignature(policy, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));

            if (FullUri)
            {
                string fullUri = queue.Uri.ToString() + sasToken;
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
Beispiel #16
0
        public override void ExecuteCmdlet()
        {
            CloudBlob blob = null;

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

            // When the input context is Oauth bases, can't generate normal SAS, but UserDelegationSas
            bool generateUserDelegationSas = false;

            if (Channel != null && Channel.StorageContext != null && Channel.StorageContext.StorageAccount.Credentials.IsToken)
            {
                if (ShouldProcess(blob.Name, "Generate User Delegation SAS, since input Storage Context is OAuth based."))
                {
                    generateUserDelegationSas = true;
                    if (!string.IsNullOrEmpty(accessPolicyIdentifier))
                    {
                        throw new ArgumentException("When input Storage Context is OAuth based, Saved Policy is not supported.", "Policy");
                    }
                }
                else
                {
                    return;
                }
            }

            if (!(blob is InvalidCloudBlob) && !UseTrack2SDK())
            {
                SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
                bool shouldSetExpiryTime            = SasTokenHelper.ValidateContainerAccessPolicy(Channel, blob.Container.Name, accessPolicy, accessPolicyIdentifier);
                SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
                string sasToken = GetBlobSharedAccessSignature(blob, accessPolicy, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange), generateUserDelegationSas);

                if (FullUri)
                {
                    string fullUri = blob.SnapshotQualifiedUri.ToString();
                    if (blob.IsSnapshot)
                    {
                        // Since snapshot URL already has '?', need remove '?' in the first char of sas
                        fullUri = fullUri + "&" + sasToken.Substring(1);
                    }
                    else
                    {
                        fullUri = fullUri + sasToken;
                    }
                    WriteObject(fullUri);
                }
                else
                {
                    WriteObject(sasToken);
                }
            }
            else // Use Track2 SDk
            {
                BlobBaseClient blobClient;
                if (this.BlobBaseClient != null)
                {
                    blobClient = this.BlobBaseClient;
                }
                else
                {
                    blobClient = AzureStorageBlob.GetTrack2BlobClient(blob, Channel.StorageContext, this.ClientOptions);
                }

                BlobSasBuilder sasBuilder;
                if (ParameterSetName == BlobNamePipelineParmeterSetWithPolicy || ParameterSetName == BlobPipelineParameterSetWithPolicy)
                {
                    BlobContainerClient container = AzureStorageContainer.GetTrack2BlobContainerClient(Channel.GetContainerReference(blobClient.BlobContainerName), Channel.StorageContext, ClientOptions);
                    IEnumerable <BlobSignedIdentifier> signedIdentifiers = container.GetAccessPolicy(cancellationToken: CmdletCancellationToken).Value.SignedIdentifiers;
                    BlobSignedIdentifier signedIdentifier = null;
                    foreach (BlobSignedIdentifier identifier in signedIdentifiers)
                    {
                        if (identifier.Id == this.Policy)
                        {
                            signedIdentifier = identifier;
                            break;
                        }
                    }
                    if (signedIdentifier is null)
                    {
                        throw new ArgumentException(string.Format(Resources.InvalidAccessPolicy, this.Policy));
                    }
                    sasBuilder = new BlobSasBuilder
                    {
                        BlobContainerName = blobClient.BlobContainerName,
                        BlobName          = blobClient.Name,
                        Identifier        = this.Policy
                    };

                    if (this.StartTime != null)
                    {
                        if (signedIdentifier.AccessPolicy.StartsOn != DateTimeOffset.MinValue)
                        {
                            throw new InvalidOperationException(Resources.SignedStartTimeMustBeOmitted);
                        }
                        else
                        {
                            sasBuilder.StartsOn = this.StartTime.Value.ToUniversalTime();
                        }
                    }

                    if (this.ExpiryTime != null)
                    {
                        if (signedIdentifier.AccessPolicy.ExpiresOn != DateTimeOffset.MinValue)
                        {
                            throw new ArgumentException(Resources.SignedExpiryTimeMustBeOmitted);
                        }
                        else
                        {
                            sasBuilder.ExpiresOn = this.ExpiryTime.Value.ToUniversalTime();
                        }
                    }
                    else if (signedIdentifier.AccessPolicy.ExpiresOn == DateTimeOffset.MinValue)
                    {
                        if (sasBuilder.StartsOn != DateTimeOffset.MinValue)
                        {
                            sasBuilder.ExpiresOn = sasBuilder.StartsOn.ToUniversalTime().AddHours(1);
                        }
                        else
                        {
                            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                        }
                    }

                    if (this.Permission != null)
                    {
                        if (signedIdentifier.AccessPolicy.Permissions != null)
                        {
                            throw new ArgumentException(Resources.SignedPermissionsMustBeOmitted);
                        }
                        else
                        {
                            sasBuilder.SetPermissions(this.Permission);
                        }
                    }
                }
                else
                {
                    sasBuilder = new BlobSasBuilder
                    {
                        BlobContainerName = blobClient.BlobContainerName,
                        BlobName          = blobClient.Name,
                    };
                    sasBuilder.SetPermissions(this.Permission);
                    if (this.StartTime != null)
                    {
                        sasBuilder.StartsOn = this.StartTime.Value.ToUniversalTime();
                    }
                    if (this.ExpiryTime != null)
                    {
                        sasBuilder.ExpiresOn = this.ExpiryTime.Value.ToUniversalTime();
                    }
                    else
                    {
                        if (sasBuilder.StartsOn != DateTimeOffset.MinValue)
                        {
                            sasBuilder.ExpiresOn = sasBuilder.StartsOn.AddHours(1).ToUniversalTime();
                        }
                        else
                        {
                            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                        }
                    }
                }
                if (this.IPAddressOrRange != null)
                {
                    sasBuilder.IPRange = Util.SetupIPAddressOrRangeForSASTrack2(this.IPAddressOrRange);
                }
                if (this.Protocol != null)
                {
                    if (this.Protocol.Value == SharedAccessProtocol.HttpsOrHttp)
                    {
                        sasBuilder.Protocol = SasProtocol.HttpsAndHttp;
                    }
                    else //HttpsOnly
                    {
                        sasBuilder.Protocol = SasProtocol.Https;
                    }
                }
                if (Util.GetVersionIdFromBlobUri(blobClient.Uri) != null)
                {
                    sasBuilder.BlobVersionId = Util.GetVersionIdFromBlobUri(blobClient.Uri);
                }
                if (Util.GetSnapshotTimeFromBlobUri(blobClient.Uri) != null)
                {
                    sasBuilder.Snapshot = Util.GetSnapshotTimeFromBlobUri(blobClient.Uri).Value.ToString("o");
                }

                string sasToken = GetBlobSharedAccessSignature(blobClient, sasBuilder, generateUserDelegationSas);
                if (sasToken[0] != '?')
                {
                    sasToken = "?" + sasToken;
                }

                if (FullUri)
                {
                    string fullUri = blobClient.Uri.ToString();
                    if (blob.IsSnapshot)
                    {
                        // Since snapshot URL already has '?', need remove '?' in the first char of sas
                        fullUri = fullUri + "&" + sasToken.Substring(1);
                    }
                    else
                    {
                        fullUri = fullUri + sasToken;
                    }
                    WriteObject(fullUri);
                }
                else
                {
                    WriteObject(sasToken);
                }
            }
        }
        public override void ExecuteCmdlet()
        {
            if (String.IsNullOrEmpty(Name))
            {
                return;
            }

            // When the input context is Oauth bases, can't generate normal SAS, but UserDelegationSas
            bool generateUserDelegationSas = false;

            if (Channel != null && Channel.StorageContext != null && Channel.StorageContext.StorageAccount.Credentials.IsToken)
            {
                if (ShouldProcess(Name, "Generate User Delegation SAS, since input Storage Context is OAuth based."))
                {
                    generateUserDelegationSas = true;
                    if (!string.IsNullOrEmpty(accessPolicyIdentifier))
                    {
                        throw new ArgumentException("When input Storage Context is OAuth based, Saved Policy is not supported.", "Policy");
                    }
                }
                else
                {
                    return;
                }
            }

            if (!UseTrack2Sdk()) // Track1
            {
                CloudBlobContainer     container    = Channel.GetContainerReference(Name);
                SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
                bool shouldSetExpiryTime            = SasTokenHelper.ValidateContainerAccessPolicy(Channel, container.Name, accessPolicy, accessPolicyIdentifier);
                SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
                string sasToken;

                if (generateUserDelegationSas)
                {
                    UserDelegationKey userDelegationKey = Channel.GetUserDelegationKey(accessPolicy.SharedAccessStartTime, accessPolicy.SharedAccessExpiryTime, null, null, OperationContext);
                    sasToken = container.GetUserDelegationSharedAccessSignature(userDelegationKey, accessPolicy, null, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));
                }
                else
                {
                    sasToken = container.GetSharedAccessSignature(accessPolicy, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange));
                }

                if (FullUri)
                {
                    string fullUri = SasTokenHelper.GetFullUriWithSASToken(container.Uri.AbsoluteUri.ToString(), sasToken);
                    WriteObject(fullUri);
                }
                else
                {
                    WriteObject(sasToken);
                }
            }
            else //Track2
            {
                //Get container instance
                CloudBlobContainer  container_Track1 = Channel.GetContainerReference(Name);
                BlobContainerClient container        = AzureStorageContainer.GetTrack2BlobContainerClient(container_Track1, Channel.StorageContext, ClientOptions);

                // Get contaienr saved policy if any
                Track2Models.BlobSignedIdentifier identifier = null;
                if (ParameterSetName == SasPolicyParmeterSet)
                {
                    identifier = SasTokenHelper.GetBlobSignedIdentifier(container, this.Policy, CmdletCancellationToken);
                }

                //Create SAS builder
                BlobSasBuilder sasBuilder = SasTokenHelper.SetBlobSasBuilder_FromContainer(container, identifier, this.Permission, this.StartTime, this.ExpiryTime, this.IPAddressOrRange, this.Protocol);

                //Create SAS and output it
                string sasToken = SasTokenHelper.GetBlobSharedAccessSignature(Channel.StorageContext, sasBuilder, generateUserDelegationSas, ClientOptions, CmdletCancellationToken);
                if (sasToken[0] != '?')
                {
                    sasToken = "?" + sasToken;
                }

                if (FullUri)
                {
                    string fullUri = SasTokenHelper.GetFullUriWithSASToken(container.Uri.AbsoluteUri.ToString(), sasToken);
                    WriteObject(fullUri);
                }
                else
                {
                    WriteObject(sasToken);
                }
            }
        }
Beispiel #18
0
        public override void ExecuteCmdlet()
        {
            IStorageBlobManagement localChannel = Channel;

            // When the input context is Oauth bases, can't generate normal SAS, but UserDelegationSas
            bool generateUserDelegationSas = false;

            if (Channel != null && Channel.StorageContext != null && Channel.StorageContext.StorageAccount.Credentials.IsToken)
            {
                if (ShouldProcess(this.Path, "Generate User Delegation SAS, since input Storage Context is OAuth based."))
                {
                    generateUserDelegationSas = true;
                }
                else
                {
                    return;
                }
            }

            if (this.ParameterSetName == ItemParameterSet)
            {
                if (this.InputObject.IsDirectory)
                {
                    this.FileSystem = this.InputObject.Directory.FileSystemName;
                    this.Path       = this.InputObject.Directory.Path;
                }
                else
                {
                    this.FileSystem = this.InputObject.File.FileSystemName;
                    this.Path       = this.InputObject.File.Path;
                }
            }

            DataLakeSasBuilder sasBuilder = new DataLakeSasBuilder();

            sasBuilder.FileSystemName = this.FileSystem;
            sasBuilder.Path           = this.Path;
            sasBuilder.SetPermissions(this.Permission, true);
            if (StartTime != null)
            {
                sasBuilder.StartsOn = StartTime.Value.ToUniversalTime();
            }
            if (ExpiryTime != null)
            {
                sasBuilder.ExpiresOn = ExpiryTime.Value.ToUniversalTime();
            }
            else
            {
                if (sasBuilder.StartsOn != DateTimeOffset.MinValue)
                {
                    sasBuilder.ExpiresOn = sasBuilder.StartsOn.AddHours(1).ToUniversalTime();
                }
                else
                {
                    sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
                }
            }
            if (this.IPAddressOrRange != null)
            {
                sasBuilder.IPRange = Util.SetupIPAddressOrRangeForSASTrack2(this.IPAddressOrRange);
            }
            if (this.Protocol != null)
            {
                sasBuilder.Protocol = this.Protocol.Value;
            }

            DataLakeFileSystemClient fileSystem = GetFileSystemClientByName(localChannel, this.FileSystem);

            DataLakePathClient      pathClient;
            DataLakeFileClient      fileClient;
            DataLakeDirectoryClient dirClient;

            if (GetExistDataLakeGen2Item(fileSystem, this.Path, out fileClient, out dirClient))
            {
                // Directory
                sasBuilder.IsDirectory = true;
                pathClient             = dirClient;
                //WriteDataLakeGen2Item(localChannel, dirClient);
                // sasBuilder.ToSasQueryParameters()
            }
            else
            {
                //File
                sasBuilder.IsDirectory = false;
                pathClient             = fileClient;
                //WriteDataLakeGen2Item(Channel, fileClient);
            }
            string sasToken = SasTokenHelper.GetDatalakeGen2SharedAccessSignature(Channel.StorageContext, sasBuilder, generateUserDelegationSas, DataLakeClientOptions, CmdletCancellationToken);


            if (FullUri)
            {
                string fullUri = pathClient.Uri.ToString();
                fullUri = fullUri + "?" + sasToken;
                WriteObject(fullUri);
            }
            else
            {
                WriteObject(sasToken);
            }
        }
        public override void ExecuteCmdlet()
        {
            CloudBlob blob = null;

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

            // When the input context is Oauth bases, can't generate normal SAS, but UserDelegationSas
            bool generateUserDelegationSas = false;

            if (Channel != null && Channel.StorageContext != null && Channel.StorageContext.StorageAccount.Credentials.IsToken)
            {
                if (ShouldProcess(blob.Name, "Generate User Delegation SAS, since input Storage Context is OAuth based."))
                {
                    generateUserDelegationSas = true;
                    if (!string.IsNullOrEmpty(accessPolicyIdentifier))
                    {
                        throw new ArgumentException("When input Storage Context is OAuth based, Saved Policy is not supported.", "Policy");
                    }
                }
                else
                {
                    return;
                }
            }

            if (!(blob is InvalidCloudBlob) && !UseTrack2Sdk())
            {
                SharedAccessBlobPolicy accessPolicy = new SharedAccessBlobPolicy();
                bool shouldSetExpiryTime            = SasTokenHelper.ValidateContainerAccessPolicy(Channel, blob.Container.Name, accessPolicy, accessPolicyIdentifier);
                SetupAccessPolicy(accessPolicy, shouldSetExpiryTime);
                string sasToken = GetBlobSharedAccessSignature(blob, accessPolicy, accessPolicyIdentifier, Protocol, Util.SetupIPAddressOrRangeForSAS(IPAddressOrRange), generateUserDelegationSas);

                if (FullUri)
                {
                    string fullUri = blob.SnapshotQualifiedUri.ToString();
                    if (blob.IsSnapshot)
                    {
                        // Since snapshot URL already has '?', need remove '?' in the first char of sas
                        fullUri = fullUri + "&" + sasToken.Substring(1);
                    }
                    else
                    {
                        fullUri = fullUri + sasToken;
                    }
                    WriteObject(fullUri);
                }
                else
                {
                    WriteObject(sasToken);
                }
            }
            else // Use Track2 SDk
            {
                //Get blob instance
                BlobBaseClient blobClient;
                if (this.BlobBaseClient != null)
                {
                    blobClient = this.BlobBaseClient;
                }
                else
                {
                    blobClient = AzureStorageBlob.GetTrack2BlobClient(blob, Channel.StorageContext, this.ClientOptions);
                }

                // Get contaienr saved policy if any
                BlobSignedIdentifier identifier = null;
                if (ParameterSetName == BlobNamePipelineParmeterSetWithPolicy || ParameterSetName == BlobPipelineParameterSetWithPolicy)
                {
                    BlobContainerClient container = AzureStorageContainer.GetTrack2BlobContainerClient(Channel.GetContainerReference(blobClient.BlobContainerName), Channel.StorageContext, ClientOptions);
                    identifier = SasTokenHelper.GetBlobSignedIdentifier(container, this.Policy, CmdletCancellationToken);
                }

                //Create SAS builder
                BlobSasBuilder sasBuilder = SasTokenHelper.SetBlobSasBuilder_FromBlob(blobClient, identifier, this.Permission, this.StartTime, this.ExpiryTime, this.IPAddressOrRange, this.Protocol);

                //Create SAS and ourput
                string sasToken = SasTokenHelper.GetBlobSharedAccessSignature(Channel.StorageContext, sasBuilder, generateUserDelegationSas, ClientOptions, CmdletCancellationToken);
                if (sasToken[0] != '?')
                {
                    sasToken = "?" + sasToken;
                }

                if (FullUri)
                {
                    string fullUri = blobClient.Uri.ToString();
                    if (blob.IsSnapshot)
                    {
                        // Since snapshot URL already has '?', need remove '?' in the first char of sas
                        fullUri = fullUri + "&" + sasToken.Substring(1);
                    }
                    else
                    {
                        fullUri = fullUri + sasToken;
                    }
                    WriteObject(fullUri);
                }
                else
                {
                    WriteObject(sasToken);
                }
            }
        }
        public void ValidateExistingPolicyWithEmptyPoliciesTest()
        {
            Dictionary <string, string> policies = new Dictionary <string, string>();

            AssertThrows <ArgumentException>(() => SasTokenHelper.GetExistingPolicy <string>(policies, "test1"));
        }