public DataLakeServiceClient GetServiceClient_DataLakeServiceIdentitySas_Path( string fileSystemName, string path, UserDelegationKey userDelegationKey, DataLakeSasQueryParameters sasCredentials = default) => InstrumentClient( new DataLakeServiceClient( (new Uri($"{TestConfigHierarchicalNamespace.BlobServiceEndpoint}?{sasCredentials ?? GetNewDataLakeServiceIdentitySasCredentialsPath(fileSystemName: fileSystemName, path: path, userDelegationKey: userDelegationKey, accountName: TestConfigHierarchicalNamespace.AccountName)}")).ToHttps(), GetOptions()));
public BlobServiceClient GetServiceClient_BlobServiceIdentitySas_Blob( string containerName, string blobName, UserDelegationKey userDelegationKey, BlobSasQueryParameters sasCredentials = default) => InstrumentClient( new BlobServiceClient( new Uri($"{TestConfigOAuth.BlobServiceEndpoint}?{sasCredentials ?? GetNewBlobServiceIdentitySasCredentialsBlob(containerName: containerName, blobName: blobName, userDelegationKey: userDelegationKey, accountName: TestConfigOAuth.AccountName)}"), GetOptions()));
public BlobSasQueryParameters GetContainerIdentitySas( string containerName, BlobContainerSasPermissions permissions, UserDelegationKey userDelegationKey, string accountName, string sasVersion = default) { BlobSasBuilder sasBuilder = GetBlobSasBuilder(containerName, sasVersion: sasVersion); sasBuilder.SetPermissions(permissions); return sasBuilder.ToSasQueryParameters(userDelegationKey, accountName); }
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); } }
private async Task <Uri> GetUserDelegationSasBlobUri(string blobName) { // Construct the blob endpoint from the account name. var blobEndpoint = $"https://{_config["StorageAccount:Name"]}.blob.core.windows.net"; // Create a new Blob service client with Azure AD credentials. var blobClient = new BlobServiceClient(new Uri(blobEndpoint), AuthenticationHelper.GetTokenCredential(_config)); // Get a user delegation key for the Blob service that's valid for 10 minutes. // You can use the key to generate any number of shared access signatures over the lifetime of the key. UserDelegationKey key = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddMinutes(10)); // Read the key's properties. _logger.LogInformation("User delegation key properties:"); _logger.LogInformation("Key signed start: {0}", key.SignedStartsOn); _logger.LogInformation("Key signed expiry: {0}", key.SignedExpiresOn); _logger.LogInformation("Key signed object ID: {0}", key.SignedObjectId); _logger.LogInformation("Key signed tenant ID: {0}", key.SignedTenantId); _logger.LogInformation("Key signed service: {0}", key.SignedService); _logger.LogInformation("Key signed version: {0}", key.SignedVersion); // Create a SAS token that's valid for one hour. var sasBuilder = new BlobSasBuilder() { BlobContainerName = _config["StorageAccount:ContainerName"], BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddMinutes(10) }; // Specify write permissions for the SAS. sasBuilder.SetPermissions(BlobSasPermissions.Write); // Use the key to get the SAS token. var sasToken = sasBuilder.ToSasQueryParameters(key, _config["StorageAccount:Name"]).ToString(); // Construct the full URI, including the SAS token. var fullUri = new UriBuilder() { Scheme = "https", Host = $"{_config["StorageAccount:Name"]}.blob.core.windows.net", Path = $"{_config["StorageAccount:ContainerName"]}/{blobName}", Query = sasToken }; _logger.LogInformation("User delegation SAS URI: {0}", fullUri); return(fullUri.Uri); }
/// <summary> /// Get blob shared access signature /// </summary> /// <param name="blob">CloudBlob object</param> /// <param name="accessPolicy">SharedAccessBlobPolicy object</param> /// <param name="policyIdentifier">The existing policy identifier.</param> /// <returns></returns> private string GetBlobSharedAccessSignature(CloudBlob blob, SharedAccessBlobPolicy accessPolicy, string policyIdentifier, SharedAccessProtocol? protocol, IPAddressOrRange iPAddressOrRange, bool generateUserDelegationSas) { CloudBlobContainer container = blob.Container; if (generateUserDelegationSas) { UserDelegationKey userDelegationKey = Channel.GetUserDelegationKey(accessPolicy.SharedAccessStartTime, accessPolicy.SharedAccessExpiryTime, null, null, OperationContext); return blob.GetUserDelegationSharedAccessSignature(userDelegationKey, accessPolicy, null, protocol, iPAddressOrRange); } else { return blob.GetSharedAccessSignature(accessPolicy, null, policyIdentifier, protocol, iPAddressOrRange); } }
/// <summary> /// Returns an user-delegation-based shared access signature for the container, with credentials solely based on the <see cref="UserDelegationKey"/> provided. /// </summary> /// <param name="delegationKey"><see cref="UserDelegationKey"/> for signing this SAS token.</param> /// <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 container accessed with this SAS.</param> /// <param name="protocols">The allowed protocols (https only, or http and https). Null if you don't want to restrict protocol.</param> /// <param name="ipAddressOrRange">The allowed IP address or IP address range. Null if you don't want to restrict based on IP address.</param> /// <returns></returns> public string GetUserDelegationSharedAccessSignature( UserDelegationKey delegationKey, SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers = default(SharedAccessBlobHeaders), SharedAccessProtocol?protocols = default(SharedAccessProtocol?), IPAddressOrRange ipAddressOrRange = default(IPAddressOrRange)) { string resourceName = this.GetSharedAccessCanonicalName(); string signature = BlobSharedAccessSignatureHelper.GetHash(policy, headers, resourceName, Constants.HeaderConstants.TargetStorageVersion, Constants.QueryConstants.ContainerResourceType, null /* snapshotTime */, protocols, ipAddressOrRange, delegationKey); UriQueryBuilder builder = BlobSharedAccessSignatureHelper.GetSignature(policy, headers, null, Constants.QueryConstants.ContainerResourceType, signature, null, Constants.HeaderConstants.TargetStorageVersion, protocols, ipAddressOrRange, delegationKey); return(builder.ToString()); }
public BlobSasQueryParameters GetSnapshotIdentitySas( string containerName, string blobName, string snapshot, SnapshotSasPermissions permissions, UserDelegationKey userDelegationKey, string accountName, string sasVersion = default) { BlobSasBuilder sasBuilder = GetBlobSasBuilder(containerName, blobName, snapshot: snapshot, sasVersion: sasVersion); sasBuilder.SetPermissions(permissions); return(sasBuilder.ToSasQueryParameters(userDelegationKey, accountName)); }
public static string CreateSASToken(string BlobStorageAccountName, string BlobStorageContainerName, string BlobStorageFolderPath, string DataFileName, int accessDuration) { // Get a credential and create a client object for the blob container. Note using new Azure Core credential flow BlobServiceClient blobClient = new BlobServiceClient(new Uri(BlobStorageAccountName), new DefaultAzureCredential()); //blobClient.GetProperties(); var startDate = DateTimeOffset.UtcNow.AddMinutes(-1); var endDate = DateTimeOffset.UtcNow.AddDays(accessDuration); // Get a user delegation key for the Blob service that's valid for seven days. // You can use the key to generate any number of shared access signatures over the lifetime of the key. UserDelegationKey key = blobClient.GetUserDelegationKey(startDate, endDate); Uri BlobUri = new Uri(BlobStorageAccountName); BlobContainerClient containerClient = new BlobContainerClient(BlobUri, new DefaultAzureCredential()); // Create a SAS token BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = BlobStorageContainerName, BlobName = String.Format("{0}{1}", BlobStorageFolderPath, DataFileName), Resource = "b", StartsOn = startDate, ExpiresOn = endDate, Protocol = SasProtocol.Https }; // Specify read permissions for the SAS. BlobSasPermissions perms = BlobSasPermissions.Create | BlobSasPermissions.Write; sasBuilder.SetPermissions(perms); // Use the key to get the SAS token. string sasToken = sasBuilder.ToSasQueryParameters(key, BlobUri.Host.Split('.')[0]).ToString(); // Construct the full URI, including the SAS token. UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = string.Format("{0}.blob.core.windows.net", BlobUri.Host.Split('.')[0]), Path = string.Format("{0}/{1}{2}", BlobStorageContainerName, BlobStorageFolderPath, DataFileName), Query = sasToken }; string retvar = "&Path=" + Uri.EscapeDataString(fullUri.Path.ToString()); retvar += "&" + sasToken; return(retvar); }
private async static Task <Uri> GetUserDelegationSasBlob(string containerName, string blobName) { // Construct the blob endpoint from the account name. string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", Settings.StorageAccount); var credential = new ClientSecretCredential( Settings.TenantId, Settings.ClientId, Settings.ClientSecret, new TokenCredentialOptions()); // Create a new Blob service client with Azure AD credentials. BlobServiceClient blobClient = new BlobServiceClient(new Uri(blobEndpoint), credential); // Get a user delegation key for the Blob service that's valid for seven days. // You can use the key to generate any number of shared access signatures over the lifetime of the key. UserDelegationKey key = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); // Create a SAS token that's valid for one hour. BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; // Specify read permissions for the SAS. sasBuilder.SetPermissions(BlobSasPermissions.Read); // Use the key to get the SAS token. string sasToken = sasBuilder.ToSasQueryParameters(key, Settings.StorageAccount).ToString(); // Construct the full URI, including the SAS token. UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = string.Format("{0}.blob.core.windows.net", Settings.StorageAccount), Path = string.Format("{0}/{1}", containerName, blobName), Query = sasToken }; return(fullUri.Uri); }
public async Task <string> GetFileUrl(string fileName) { //BlobClient blobClient = containerClient.GetBlobClient(fileName); //if (! await blobClient.ExistsAsync()) // return null; //return blobClient.Uri.AbsoluteUri; ////var key = await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, //// DateTimeOffset.UtcNow.AddDays(7)); //string blobEndpoint = string.Format("https://{0}.blob.core.windows.net", ACCOUNT_NAME); string blobEndpoint = END_POINT; BlobServiceClient blobClient = new BlobServiceClient(new Uri(blobEndpoint), new DefaultAzureCredential()); UserDelegationKey key = await blobClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = CONTAINER_NAME, BlobName = fileName, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; sasBuilder.SetPermissions(BlobAccountSasPermissions.Read); string sasToken = sasBuilder.ToSasQueryParameters(key, ACCOUNT_NAME).ToString(); UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = /*string.Format("{0}.blob.core.windows.net", accountName)*/ END_POINT, Path = string.Format("{0}/{1}", CONTAINER_NAME, fileName), Query = sasToken }; return(fullUri.Uri.AbsoluteUri); }
static void Main(string[] args) { string storageAccount = "az204testing"; DateTimeOffset startTimeKey = DateTimeOffset.UtcNow; DateTimeOffset endTimeKey = DateTimeOffset.UtcNow.AddDays(7); DateTimeOffset startTimeSAS = startTimeKey; DateTimeOffset endTimeSAS = startTimeSAS.AddDays(1); Uri blobEndpointUri = new Uri($"https://{storageAccount}.blob.core.windows.net"); var defaultCredentials = new DefaultAzureCredential(true); BlobServiceClient blobClient = new BlobServiceClient(blobEndpointUri, defaultCredentials); //Get the key. We are going to use this key for creating the SAS UserDelegationKey key = blobClient.GetUserDelegationKey(startTimeKey, endTimeKey); System.Console.WriteLine($"User Key Starts on: {key.SignedStartsOn}"); System.Console.WriteLine($"User Key Expires on: {key.SignedExpiresOn}"); System.Console.WriteLine($"User Key Service: {key.SignedService}"); System.Console.WriteLine($"User Key Version: {key.SignedVersion}"); //We need to use the BlobSasBuilder for creating the SAS BlobSasBuilder blobSasBuilder = new BlobSasBuilder() { StartsOn = startTimeSAS, ExpiresOn = endTimeSAS }; //We set the permissions Create, List, Add, Read, and Write blobSasBuilder.SetPermissions("clarw"); string sasToken = blobSasBuilder.ToSasQueryParameters (key, storageAccount).ToString(); System.Console.WriteLine($"SAS Token: {sasToken}"); }
// </Snippet_ReadBlobWithSasAsync> #endregion #region // <Snippet_GetUserDelegationSasContainer> async static Task <Uri> GetUserDelegationSasContainer(BlobContainerClient blobContainerClient) { BlobServiceClient blobServiceClient = blobContainerClient.GetParentBlobServiceClient(); // Get a user delegation key for the Blob service that's valid for seven days. // You can use the key to generate any number of shared access signatures // over the lifetime of the key. UserDelegationKey userDelegationKey = await blobServiceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); // Create a SAS token that's valid for seven days. BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = blobContainerClient.Name, Resource = "c", ExpiresOn = DateTimeOffset.UtcNow.AddDays(7) }; // Specify racwl permissions for the SAS. sasBuilder.SetPermissions( BlobContainerSasPermissions.Read | BlobContainerSasPermissions.Add | BlobContainerSasPermissions.Create | BlobContainerSasPermissions.Write | BlobContainerSasPermissions.List ); // Add the SAS token to the container URI. BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobContainerClient.Uri) { // Specify the user delegation key. Sas = sasBuilder.ToSasQueryParameters(userDelegationKey, blobServiceClient.AccountName) }; Console.WriteLine("Container user delegation SAS URI: {0}", blobUriBuilder); Console.WriteLine(); return(blobUriBuilder.ToUri()); }
private async Task <string> GenerateSasUrl(string containerName, string blobName) { var storageAccount = Environment.GetEnvironmentVariable("AZURE_STORAGE_ACCOUNT_NAME"); // Create a BlobServiceClient that will authenticate through Active Directory Uri accountUri = new Uri(String.Format("https://{0}.blob.core.windows.net/", storageAccount)); BlobServiceClient client = new BlobServiceClient(accountUri, new DefaultAzureCredential()); var containerClient = client.GetBlobContainerClient(containerName); // Create a SAS token that's valid for one hour. BlobSasBuilder sasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, BlobName = blobName, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddHours(1) }; // Specify read permissions for the SAS. sasBuilder.SetPermissions(BlobSasPermissions.Read); UserDelegationKey key = await client.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); string sasToken = sasBuilder.ToSasQueryParameters(key, storageAccount).ToString(); // Construct the full URI, including the SAS token. UriBuilder fullUri = new UriBuilder() { Scheme = "https", Host = string.Format("{0}.blob.core.windows.net", storageAccount), Path = string.Format("{0}/{1}", containerName, blobName), Query = sasToken }; return(fullUri.ToString()); }
internal static async Task <UserDelegationKey> ParseAsync(Stream stream, CancellationToken token) { UserDelegationKey key = null; using (XmlReader reader = XMLReaderExtensions.CreateAsAsync(stream)) { token.ThrowIfCancellationRequested(); if (await reader.ReadToFollowingAsync(Constants.UserDelegationKey).ConfigureAwait(false)) { if (reader.IsEmptyElement) { await reader.SkipAsync().ConfigureAwait(false); } else { key = await ParseKey(reader, token); } } } return(key); }
public BlobSasQueryParameters GetNewBlobServiceIdentitySasCredentialsContainer(string containerName, UserDelegationKey userDelegationKey, string accountName) { var builder = GetBlobSasBuilder(containerName); builder.SetPermissions(BlobContainerSasPermissions.All); return(builder.ToSasQueryParameters(userDelegationKey, accountName)); }
public DataLakeSasQueryParameters GetNewDataLakeServiceIdentitySasCredentialsPath(string fileSystemName, string path, UserDelegationKey userDelegationKey, string accountName) { var builder = new DataLakeSasBuilder { FileSystemName = fileSystemName, Path = path, Protocol = SasProtocol.None, StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(+1), IPRange = new SasIPRange(IPAddress.None, IPAddress.None) }; builder.SetPermissions( DataLakeSasPermissions.Read | DataLakeSasPermissions.Add | DataLakeSasPermissions.Create | DataLakeSasPermissions.Delete | DataLakeSasPermissions.Write); return(builder.ToSasQueryParameters(userDelegationKey, accountName)); }
public BlobSasQueryParameters GetNewBlobServiceIdentitySasCredentialsBlob(string containerName, string blobName, UserDelegationKey userDelegationKey, string accountName) => new BlobSasBuilder { BlobContainerName = containerName, BlobName = blobName, Protocol = SasProtocol.None, StartTime = Recording.UtcNow.AddHours(-1), ExpiryTime = Recording.UtcNow.AddHours(+1), Permissions = new BlobSasPermissions { Read = true, Add = true, Create = true, Write = true, Delete = true }.ToString(), IPRange = new IPRange(IPAddress.None, IPAddress.None) } .ToSasQueryParameters(userDelegationKey, accountName);
public DataLakeSasQueryParameters GetNewDataLakeSasCredentialsOwner(string fileSystemName, string ownerName, UserDelegationKey userDelegationKey, string accountName) { DataLakeSasBuilder dataLakeSasBuilder = new DataLakeSasBuilder { StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(1), FileSystemName = fileSystemName, AgentObjectId = ownerName }; dataLakeSasBuilder.SetPermissions(DataLakeSasPermissions.All); return(dataLakeSasBuilder.ToSasQueryParameters(userDelegationKey, accountName)); }
/// <summary> /// Get the signature hash embedded inside the User Delegation 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="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="resourceIdentifier">Resource type id string.</param> /// <param name="snapTime">Time of snapshot if applicable.</param> /// <param name="protocols">The HTTP/HTTPS protocols for Account SAS.</param> /// <param name="ipAddressOrRange">The IP range for IPSAS.</param> /// <param name="delegationKey">The user delegaion key used for signing.</param> /// <returns>The signed hash.</returns> internal static string GetHash( SharedAccessBlobPolicy policy, SharedAccessBlobHeaders headers, string resourceName, string sasVersion, string resourceIdentifier, DateTimeOffset?snapTime, SharedAccessProtocol?protocols, IPAddressOrRange ipAddressOrRange, UserDelegationKey delegationKey) { CommonUtility.AssertNotNullOrEmpty("resourceName", resourceName); CommonUtility.AssertNotNullOrEmpty("sasVersion", sasVersion); CommonUtility.AssertNotNull("delegationKey", delegationKey); CommonUtility.AssertNotNull("delegationKey.SignedOid", delegationKey.SignedOid); CommonUtility.AssertNotNull("delegationKey.SignedTid", delegationKey.SignedTid); CommonUtility.AssertNotNull("delegationKey.SignedStart", delegationKey.SignedStart); CommonUtility.AssertNotNull("delegationKey.SignedExpiry", delegationKey.SignedExpiry); CommonUtility.AssertNotNullOrEmpty("delegationKey.SignedService", delegationKey.SignedService); CommonUtility.AssertNotNullOrEmpty("delegationKey.SignedVersion", delegationKey.SignedVersion); CommonUtility.AssertNotNullOrEmpty("delegationKey.Value", delegationKey.Value); CommonUtility.AssertNotNull("policy", policy); CommonUtility.AssertNotNull("policy.SharedAccessExpiryTime", policy.SharedAccessExpiryTime); CommonUtility.AssertNotNullOrEmpty("policy.Permissions", SharedAccessBlobPolicy.PermissionsToString(policy.Permissions)); string permissions = SharedAccessBlobPolicy.PermissionsToString(policy.Permissions); DateTimeOffset?startTime = policy.SharedAccessStartTime; DateTimeOffset?expiryTime = policy.SharedAccessExpiryTime; //// StringToSign = signedpermissions + "\n" + //// signedstart + "\n" + //// signedexpiry + "\n" + //// canonicalizedresource + "\n" + //// signedoid + "\n" + //// signedtid + "\n" + //// signedkeystart + "\n" + //// signedkeyexpiry + "\n" + //// signedkeyservice + "\n" + //// signedkeyverion + "\n" + //// signedIP + "\n" + //// signedProtocol + "\n" + //// signedversion + "\n" + //// signedResourceIdentifier + "\n" + //// signedTimeStamp + "\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}\n{13}\n{14}\n{15}\n{16}\n{17}\n{18}\n{19}", permissions, SharedAccessSignatureHelper.GetDateTimeOrEmpty(startTime), SharedAccessSignatureHelper.GetDateTimeOrEmpty(expiryTime), resourceName, delegationKey.SignedOid, delegationKey.SignedTid, delegationKey.SignedStart.Value.UtcDateTime.ToString(Constants.DateTimeFormatter), delegationKey.SignedExpiry.Value.UtcDateTime.ToString(Constants.DateTimeFormatter), delegationKey.SignedService, delegationKey.SignedVersion, ipAddressOrRange == null ? string.Empty : ipAddressOrRange.ToString(), SharedAccessSignatureHelper.GetProtocolString(protocols), sasVersion, resourceIdentifier, snapTime.ToString(), cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); Logger.LogVerbose(null /* operationContext */, SR.TraceStringToSign, stringToSign); return(CryptoUtility.ComputeHmac256(Convert.FromBase64String(delegationKey.Value), stringToSign)); }
public BlobSasQueryParameters GetNewBlobServiceIdentitySasCredentialsBlob(string containerName, string blobName, UserDelegationKey userDelegationKey, string accountName) { var builder = new BlobSasBuilder { BlobContainerName = containerName, BlobName = blobName, Protocol = SasProtocol.None, StartsOn = Recording.UtcNow.AddHours(-1), ExpiresOn = Recording.UtcNow.AddHours(+1), IPRange = new SasIPRange(IPAddress.None, IPAddress.None) }; builder.SetPermissions( BlobSasPermissions.Read | BlobSasPermissions.Add | BlobSasPermissions.Create | BlobSasPermissions.Delete | BlobSasPermissions.Write); return(builder.ToSasQueryParameters(userDelegationKey, accountName)); }
/// <summary> /// Use an account's <see cref="UserDelegationKey"/> to sign this /// shared access signature values to produce the proper SAS query /// parameters for authenticating requests. /// </summary> /// <param name="userDelegationKey"> /// A <see cref="UserDelegationKey"/> returned from /// <see cref="Azure.Storage.Blobs.BlobServiceClient.GetUserDelegationKeyAsync"/>. /// </param> /// <param name="accountName">The name of the storage account.</param> /// <returns> /// The <see cref="BlobSasQueryParameters"/> used for authenticating requests. /// </returns> public BlobSasQueryParameters ToSasQueryParameters(UserDelegationKey userDelegationKey, string accountName) { userDelegationKey = userDelegationKey ?? throw Errors.ArgumentNull(nameof(userDelegationKey)); EnsureState(); var startTime = SasQueryParameters.FormatTimesForSasSigning(StartTime); var expiryTime = SasQueryParameters.FormatTimesForSasSigning(ExpiryTime); var signedStart = SasQueryParameters.FormatTimesForSasSigning(userDelegationKey.SignedStart); var signedExpiry = SasQueryParameters.FormatTimesForSasSigning(userDelegationKey.SignedExpiry); // See http://msdn.microsoft.com/en-us/library/azure/dn140255.aspx var stringToSign = String.Join("\n", Permissions, startTime, expiryTime, GetCanonicalName(accountName, BlobContainerName ?? String.Empty, BlobName ?? String.Empty), userDelegationKey.SignedObjectId, userDelegationKey.SignedTenantId, signedStart, signedExpiry, userDelegationKey.SignedService, userDelegationKey.SignedVersion, IPRange.ToString(), Protocol.ToString(), Version, Resource, Snapshot, CacheControl, ContentDisposition, ContentEncoding, ContentLanguage, ContentType); var signature = ComputeHMACSHA256(userDelegationKey.Value, stringToSign); var p = new BlobSasQueryParameters( version: Version, services: null, resourceTypes: null, protocol: Protocol, startTime: StartTime, expiryTime: ExpiryTime, ipRange: IPRange, identifier: null, resource: Resource, permissions: Permissions, keyOid: userDelegationKey.SignedObjectId, keyTid: userDelegationKey.SignedTenantId, keyStart: userDelegationKey.SignedStart, keyExpiry: userDelegationKey.SignedExpiry, keyService: userDelegationKey.SignedService, keyVersion: userDelegationKey.SignedVersion, signature: signature, cacheControl: CacheControl, contentDisposition: ContentDisposition, contentEncoding: ContentEncoding, contentLanguage: ContentLanguage, contentType: ContentType); return(p); }
public BlobSasQueryParameters GetNewBlobServiceIdentitySasCredentialsBlob(string containerName, string blobName, UserDelegationKey userDelegationKey, string accountName) { var builder = GetBlobSasBuilder(containerName, blobName); builder.SetPermissions( BlobSasPermissions.Read | BlobSasPermissions.Add | BlobSasPermissions.Create | BlobSasPermissions.Delete | BlobSasPermissions.Write); return(builder.ToSasQueryParameters(userDelegationKey, accountName)); }
public static SasQueryParameters GetNewBlobServiceIdentitySasCredentialsContainer(string containerName, UserDelegationKey userDelegationKey, string accountName) => new BlobSasBuilder { ContainerName = containerName, Protocol = SasProtocol.None, StartTime = DateTimeOffset.UtcNow.AddHours(-1), ExpiryTime = DateTimeOffset.UtcNow.AddHours(+1), Permissions = new ContainerSasPermissions { Read = true, Add = true, Create = true, Write = true, Delete = true, List = true }.ToString(), IPRange = new IPRange { Start = IPAddress.None, End = IPAddress.None } } .ToSasQueryParameters(userDelegationKey, accountName);
private async Task UpdateDelegationKey() { _delegationKey = await _serviceClient.GetUserDelegationKeyAsync(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); }
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); } } }
static void MainUse(string[] args) { string storageAccount = "az204testing"; string containerName = "az204-blob-testing"; string blobName = System.IO.Path.GetRandomFileName(); DateTimeOffset startTimeKey = DateTimeOffset.UtcNow; DateTimeOffset endTimeKey = DateTimeOffset.UtcNow.AddDays(7); DateTimeOffset startTimeSAS = startTimeKey; DateTimeOffset endTimeSAS = startTimeSAS.AddYears(1); Uri blobEndpointUri = new Uri($"https://{storageAccount}.blob.core.windows.net"); var defaultCredentials = new DefaultAzureCredential(true); BlobServiceClient blobClient = new BlobServiceClient(blobEndpointUri, defaultCredentials); //Get the key. We are going to use this key for creating the SAS UserDelegationKey key = blobClient.GetUserDelegationKey(startTimeKey, endTimeKey); Console.WriteLine($"User Key Starts on: {key.SignedStartsOn}"); Console.WriteLine($"User Key Expires on: {key.SignedExpiresOn}"); Console.WriteLine($"User Key Service: {key.SignedService}"); Console.WriteLine($"User Key Version: {key.SignedVersion}"); //We need to use the BlobSasBuilder for creating the SAS BlobSasBuilder blobSasBuilder = new BlobSasBuilder() { BlobContainerName = containerName, BlobName = blobName, Resource = "b", StartsOn = startTimeSAS, ExpiresOn = endTimeSAS, Protocol = Azure.Storage.Sas.SasProtocol.Https }; //We set the permissions Create, List, Add, Read, and Write blobSasBuilder.SetPermissions(BlobSasPermissions.All); string sasToken = blobSasBuilder.ToSasQueryParameters (key, storageAccount).ToString(); Console.WriteLine($"SAS Token: {sasToken}"); //We construct the full URI for accessing the Azure Storage Account UriBuilder blobUri = new UriBuilder() { Scheme = "https", Host = $"{storageAccount}.blob.core.windows.net", Path = $"{containerName}/{blobName}", Query = sasToken }; //We create a random text file using (System.IO.StreamWriter sw = System.IO.File.CreateText(blobName)) { sw.Write("This is a testing blob for uploading using user delegated SAS tokens"); } BlobClient testingBlob = new BlobClient(blobUri.Uri); testingBlob.Upload(blobName); //Now we download the blob again and print the content. Console.WriteLine($"Reading content from testing blob {blobName}"); Console.WriteLine(); BlobDownloadInfo downloadInfo = testingBlob.Download(); using (StreamReader sr = new StreamReader(downloadInfo.Content, true)) { string line; while ((line = sr.ReadLine()) != null) { Console.WriteLine(line); } } Console.WriteLine(); Console.WriteLine("Finished reading content from testing blob"); }