コード例 #1
0
        /// <summary>
        /// Creates a <see cref="ServiceClient"/> using SAS token and the specified transport type.
        /// </summary>
        /// <param name="hostName">IoT hub host name.</param>
        /// <param name="credential">Credential that generates a SAS token to authenticate with IoT hub. See <see cref="AzureSasCredential"/>.</param>
        /// <param name="transportType">Specifies whether Amqp or Amqp_WebSocket_Only transport is used.</param>
        /// <param name="transportSettings">Specifies the AMQP_WS and HTTP proxy settings for service client.</param>
        /// <param name="options">The options that allow configuration of the service client instance during initialization.</param>
        /// <returns>An instance of <see cref="ServiceClient"/>.</returns>
        public static ServiceClient Create(
            string hostName,
            AzureSasCredential credential,
            TransportType transportType = TransportType.Amqp,
            ServiceClientTransportSettings transportSettings = default,
            ServiceClientOptions options = default)
        {
            if (string.IsNullOrEmpty(hostName))
            {
                throw new ArgumentNullException(nameof(hostName), "Parameter cannot be null or empty.");
            }

            if (credential == null)
            {
                throw new ArgumentNullException(nameof(credential));
            }

            var  sasCredentialProperties = new IotHubSasCredentialProperties(hostName, credential);
            bool useWebSocketOnly        = transportType == TransportType.Amqp_WebSocket_Only;

            return(new AmqpServiceClient(
                       sasCredentialProperties,
                       useWebSocketOnly,
                       transportSettings ?? new ServiceClientTransportSettings(),
                       options));
        }
コード例 #2
0
        public async Task AuthenticateWithSasToken()
        {
            string topicEndpoint  = TestEnvironment.TopicHost;
            string topicAccessKey = TestEnvironment.TopicKey;

            // Create the publisher client using an AzureKeyCredential
            // Custom topic should be configured to accept events of the Event Grid schema
            #region Snippet:GenerateSas
            var    builder       = new EventGridSasBuilder(new Uri(topicEndpoint), DateTimeOffset.Now.AddHours(1));
            var    keyCredential = new AzureKeyCredential(topicAccessKey);
            string sasToken      = builder.GenerateSas(keyCredential);
            #endregion

            #region Snippet:AuthenticateWithSas
            var sasCredential = new AzureSasCredential(sasToken);
            EventGridPublisherClient client = new EventGridPublisherClient(
                new Uri(topicEndpoint),
                sasCredential);
            #endregion

            // Add EventGridEvents to a list to publish to the topic
            List <EventGridEvent> eventsList = new List <EventGridEvent>
            {
                new EventGridEvent(
                    "ExampleEventSubject",
                    "Example.EventType",
                    "1.0",
                    "This is the event data")
            };

            // Send the events
            await client.SendEventsAsync(eventsList);
        }
コード例 #3
0
 public IotHubSasCredentialProperties(string hostName, AzureSasCredential credential) : base(hostName)
 {
     _credential  = credential;
     AmqpAudience = new List <string> {
         AccessRights.ServiceConnect.ToString()
     };
 }
        public async Task RegistryManager_Http_SasCredentialAuth_Renewed_Success()
        {
            // arrange
            string signature     = Configuration.IoTHub.GetIotHubSharedAccessSignature(TimeSpan.FromHours(-1));
            var    sasCredential = new AzureSasCredential(signature);

            using var registryManager = RegistryManager.Create(
                      Configuration.IoTHub.GetIotHubHostName(),
                      sasCredential);

            var device = new Device(Guid.NewGuid().ToString());

            // act
            try
            {
                await registryManager.AddDeviceAsync(device).ConfigureAwait(false);

                Assert.Fail("The SAS token is expired so the call should fail with an exception");
            }
            catch (UnauthorizedException)
            {
                // Expected to be unauthorized exception.
            }
            signature = Configuration.IoTHub.GetIotHubSharedAccessSignature(TimeSpan.FromHours(1));
            sasCredential.Update(signature);
            Device createdDevice = await registryManager.AddDeviceAsync(device).ConfigureAwait(false);

            // assert
            Assert.IsNotNull(createdDevice);

            // cleanup
            await registryManager.RemoveDeviceAsync(device.Id).ConfigureAwait(false);
        }
コード例 #5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BlobChangeFeedClient"/>
 /// class.
 /// </summary>
 /// <param name="serviceUri">
 /// A <see cref="Uri"/> referencing the blob service.
 /// This is likely to be similar to "https://{account_name}.blob.core.windows.net".
 /// Must not contain shared access signature, which should be passed in the second parameter.
 /// </param>
 /// <param name="credential">
 /// The shared access signature credential used to sign requests.
 /// </param>
 /// <param name="options">
 /// Optional client options that define the transport pipeline
 /// policies for authentication, retries, etc., that are applied to
 /// every request.
 /// </param>
 /// <param name="changeFeedOptions">
 /// Change Feed-specific client options.
 /// </param>
 /// <remarks>
 /// This constructor should only be used when shared access signature needs to be updated during lifespan of this client.
 /// </remarks>
 public BlobChangeFeedClient(Uri serviceUri,
                             AzureSasCredential credential,
                             BlobClientOptions options = default,
                             BlobChangeFeedClientOptions changeFeedOptions = default)
 {
     _blobServiceClient = new BlobServiceClient(serviceUri, credential, options);
     _changeFeedOptions = changeFeedOptions;
 }
コード例 #6
0
 public TestClientWithCredentials(Uri uri, AzureSasCredential credential, TestClientOptions options) : base(uri, options)
 {
     if (credential == null)
     {
         throw new ArgumentNullException(nameof(credential));
     }
     AzureSasCredential = credential;
 }
コード例 #7
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="SharedAccessCredential" /> class.
        /// </summary>
        ///
        /// <param name="signature">The shared access signature on which to base the token.</param>
        ///
        public SharedAccessCredential(SharedAccessSignature signature)
        {
            Argument.AssertNotNull(signature, nameof(signature));

            _sharedAccessSignature = signature;
            _sourceKeyCredential   = null;
            _sourceSasCredential   = null;
        }
コード例 #8
0
 public MinimalProcessorMock(int eventBatchMaximumCount,
                             string consumerGroup,
                             string fullyQualifiedNamespace,
                             string eventHubName,
                             AzureSasCredential credential,
                             EventProcessorOptions options = default) : base(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, credential, options)
 {
 }
コード例 #9
0
        /// <summary>
        /// Adds a sink that writes log events as records in Azure Blob Storage blob (default name LogEventEntity) using the given
        /// storage account name and Shared Access Signature (SAS) URL.
        /// </summary>
        /// <param name="loggerConfiguration">The logger configuration.</param>
        /// <param name="formatter">Use a Serilog ITextFormatter such as CompactJsonFormatter to store object in data column of Azure blob</param>
        /// <param name="sharedAccessSignature">The storage account/blob SAS key.</param>
        /// <param name="accountName">The storage account name.</param>
        /// <param name="blobEndpoint">The (optional) blob endpoint. Only needed for testing.</param>
        /// <param name="restrictedToMinimumLevel">The minimum log event level required in order to write an event to the sink.</param>
        /// <param name="storageContainerName">Container where the log entries will be written to.</param>
        /// <param name="storageFileName">File name that log entries will be written to.</param>
        /// <param name="writeInBatches">Use a periodic batching sink, as opposed to a synchronous one-at-a-time sink; this alters the partition
        /// key used for the events so is not enabled by default.</param>
        /// <param name="batchPostingLimit">The maximum number of events to post in a single batch.</param>
        /// <param name="period">The time to wait between checking for event batches.</param>
        /// <param name="cloudBlobProvider">Cloud blob provider to get current log blob.</param>
        /// <param name="blobSizeLimitBytes">The maximum file size to allow before a new one is rolled, expressed in bytes.</param>
        /// <param name="retainedBlobCountLimit">The number of latest blobs to be retained in the container always. Deletes older blobs when this limit is crossed.</param>
        /// <returns>Logger configuration, allowing configuration to continue.</returns>
        /// <exception cref="ArgumentNullException">A required parameter is null.</exception>
        public static LoggerConfiguration AzureBlobStorage(
            this LoggerSinkConfiguration loggerConfiguration,
            ITextFormatter formatter,
            string sharedAccessSignature,
            string accountName,
            Uri blobEndpoint = null,
            LogEventLevel restrictedToMinimumLevel = LevelAlias.Minimum,
            string storageContainerName            = null,
            string storageFileName = null,
            bool writeInBatches    = false,
            TimeSpan?period        = null,
            int?batchPostingLimit  = null,
            ICloudBlobProvider cloudBlobProvider = null,
            long?blobSizeLimitBytes    = null,
            int?retainedBlobCountLimit = null)
        {
            if (loggerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(loggerConfiguration));
            }
            if (formatter == null)
            {
                throw new ArgumentNullException(nameof(formatter));
            }
            if (string.IsNullOrWhiteSpace(accountName))
            {
                throw new ArgumentNullException(nameof(accountName));
            }
            if (string.IsNullOrWhiteSpace(sharedAccessSignature))
            {
                throw new ArgumentNullException(nameof(sharedAccessSignature));
            }

            try
            {
                //  TODO-VPL:  very likely messed it up here, not sure what that special case was supposed to do
                //  with a no-endpoint client
                if (blobEndpoint == null)
                {
                    throw new NotSupportedException($"'{nameof(blobEndpoint)}' must be provided");
                }
                else
                {
                    var credentials       = new AzureSasCredential(sharedAccessSignature);
                    var blobServiceClient = new BlobServiceClient(blobEndpoint, credentials);

                    // We set bypassBlobCreationValidation to true explicitly here as the the SAS URL might not have enough permissions to query if the blob exists.
                    return(AzureBlobStorage(loggerConfiguration, formatter, blobServiceClient, restrictedToMinimumLevel, storageContainerName, storageFileName, writeInBatches, period, batchPostingLimit, true, cloudBlobProvider, blobSizeLimitBytes, retainedBlobCountLimit));
                }
            }
            catch (Exception ex)
            {
                Debugging.SelfLog.WriteLine($"Error configuring AzureBlobStorage: {ex}");

                ILogEventSink sink = new LoggerConfiguration().CreateLogger();
                return(loggerConfiguration.Sink(sink, restrictedToMinimumLevel));
            }
        }
コード例 #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TableServiceClient"/> using the specified <see cref="Uri" /> containing a shared access signature (SAS)
 /// token credential. See <see cref="TableClient.GetSasBuilder(TableSasPermissions, DateTimeOffset)" /> for creating a SAS token.
 /// </summary>
 /// <param name="endpoint">
 /// A <see cref="Uri"/> referencing the table service account.
 /// This is likely to be similar to "https://{account_name}.table.core.windows.net/" or "https://{account_name}.table.cosmos.azure.com/".
 /// </param>
 /// <param name="credential">The shared access signature credential used to sign requests.</param>
 /// <param name="options">
 /// Optional client options that define the transport pipeline policies for authentication, retries, etc., that are applied to every request.
 /// </param>
 public TableServiceClient(Uri endpoint, AzureSasCredential credential, TableClientOptions options = null)
     : this(endpoint, default, credential, options)
 {
     if (endpoint.Scheme != "https")
     {
         throw new ArgumentException("Cannot use TokenCredential without HTTPS.", nameof(endpoint));
     }
     Argument.AssertNotNull(credential, nameof(credential));
 }
 public MockCheckpointStoreProcessor(CheckpointStore checkpointStore,
                                     int eventBatchMaximumCount,
                                     string consumerGroup,
                                     string fullyQualifiedNamespace,
                                     string eventHubName,
                                     AzureSasCredential credential,
                                     EventProcessorOptions options = default) : base(checkpointStore, eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, credential, options)
 {
 }
コード例 #12
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="SharedAccessCredential" /> class.
        /// </summary>
        ///
        /// <param name="sourceCredential">The <see cref="AzureSasCredential"/> to base signatures on.</param>
        ///
        public SharedAccessCredential(AzureSasCredential sourceCredential)
        {
            Argument.AssertNotNull(sourceCredential, nameof(sourceCredential));

            _sourceSasCredential = sourceCredential;
            _sourceKeyCredential = null;

            _sharedAccessSignature = new SharedAccessSignature(_sourceSasCredential.Signature);
        }
コード例 #13
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="EventHubConnection"/> class.
 /// </summary>
 ///
 /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="eventHubName">The name of the specific Event Hub to associate the connection with.</param>
 /// <param name="credential">The <see cref="AzureSasCredential"/> to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
 /// <param name="connectionOptions">A set of options to apply when configuring the connection.</param>
 ///
 public EventHubConnection(string fullyQualifiedNamespace,
                           string eventHubName,
                           AzureSasCredential credential,
                           EventHubConnectionOptions connectionOptions = default) : this(fullyQualifiedNamespace,
                                                                                         eventHubName,
                                                                                         new SharedAccessCredential(credential),
                                                                                         connectionOptions)
 {
 }
コード例 #14
0
        public void SasConstructorInitializesProperties()
        {
            var signature        = new SharedAccessSignature("hub-name", "keyName", "key");
            var sourceCredential = new AzureSasCredential(signature.Value);
            var credential       = new SharedAccessCredential(sourceCredential);

            Assert.That(GetSharedAccessSignature(credential).Value, Is.EqualTo(sourceCredential.Signature), "The signature should match the source credential.");
            Assert.That(GetSourceSasCredential(credential), Is.SameAs(sourceCredential), "The source SAS credential should match.");
            Assert.That(GetSourceKeyCredential(credential), Is.Null, "The source named key credential should not be populated.");
        }
コード例 #15
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="ServiceBusConnection"/> class.
 /// </summary>
 ///
 /// <param name="fullyQualifiedNamespace">The fully qualified Service Bus namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="credential">The <see cref="AzureSasCredential"/> credential to use for authorization.  Access controls may be specified by the Service Bus namespace or the requested Service Bus entity, depending on Azure configuration.</param>
 /// <param name="options">A set of options to apply when configuring the connection.</param>
 internal ServiceBusConnection(
     string fullyQualifiedNamespace,
     AzureSasCredential credential,
     ServiceBusClientOptions options)
     : this(
         fullyQualifiedNamespace,
         new SharedAccessCredential(credential),
         options)
 {
 }
コード例 #16
0
ファイル: ApiBlobHelper.cs プロジェクト: ViktorHofer/arcade
        public async Task <IBlobContainer> GetContainerAsync(string requestedName, string targetQueue, CancellationToken cancellationToken)
        {
            ContainerInformation info = await _helixApiStorage.NewAsync(new ContainerCreationRequest(30, requestedName, targetQueue), cancellationToken).ConfigureAwait(false);

            Uri containerUri         = new Uri($"https://{info.StorageAccountName}.blob.core.windows.net/{info.ContainerName}");
            AzureSasCredential creds = new AzureSasCredential(info.WriteToken);
            var container            = new BlobContainerClient(containerUri, creds, StorageRetryPolicy.GetBlobClientOptionsRetrySettings());

            return(new Container(container, info));
        }
コード例 #17
0
        public void ConstructorWithSasCredentialValidatesOptions()
        {
            var signature      = new SharedAccessSignature("sb://fake.thing.com", "fakeKey", "fakeValue");
            var token          = new AzureSasCredential(signature.Value);
            var invalidOptions = new ServiceBusClientOptions {
                TransportType = ServiceBusTransportType.AmqpTcp, WebProxy = Mock.Of <IWebProxy>()
            };

            Assert.That(() => new ServiceBusClient("fullyQualifiedNamespace", token, invalidOptions), Throws.InstanceOf <ArgumentException>(), "The expanded argument constructor should validate client options");
        }
コード例 #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EventGridPublisherClient"/> class.
        /// </summary>
        /// <param name="endpoint">The topic endpoint. For example, "https://TOPIC-NAME.REGION-NAME-1.eventgrid.azure.net/api/events".</param>
        /// <param name="credential">The Shared Access Signature credential used to connect to Azure. This signature
        /// can be constructed using the <see cref="EventGridSasBuilder"/>.</param>
        /// <param name="options">The set of options to use for configuring the client.</param>
        public EventGridPublisherClient(Uri endpoint, AzureSasCredential credential, EventGridPublisherClientOptions options = default)
        {
            Argument.AssertNotNull(credential, nameof(credential));
            options ??= new EventGridPublisherClientOptions();
            _endpoint = endpoint;
            HttpPipeline pipeline = HttpPipelineBuilder.Build(options, new EventGridSharedAccessSignatureCredentialPolicy(credential));

            _serviceRestClient = new EventGridRestClient(new ClientDiagnostics(options), pipeline, options.Version.GetVersionString());
            _clientDiagnostics = new ClientDiagnostics(options);
        }
コード例 #19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EventGridPublisherClient"/> class.
 /// </summary>
 /// <param name="endpoint">The topic endpoint. For example, "https://TOPIC-NAME.REGION-NAME-1.eventgrid.azure.net/api/events".</param>
 /// <param name="credential">The Shared Access Signature credential used to connect to Azure. This signature
 /// can be constructed using the <see cref="EventGridSasBuilder"/>.</param>
 /// <param name="options">The set of options to use for configuring the client.</param>
 public EventGridPublisherClient(Uri endpoint, AzureSasCredential credential, EventGridPublisherClientOptions options = default)
 {
     Argument.AssertNotNull(endpoint, nameof(endpoint));
     Argument.AssertNotNull(credential, nameof(credential));
     options ??= new EventGridPublisherClientOptions();
     _uriBuilder = new RequestUriBuilder();
     _uriBuilder.Reset(endpoint);
     _uriBuilder.AppendQuery("api-version", options.Version.GetVersionString(), true);
     _pipeline          = HttpPipelineBuilder.Build(options, new EventGridSharedAccessSignatureCredentialPolicy(credential));
     _clientDiagnostics = new ClientDiagnostics(options);
 }
コード例 #20
0
        public void ConstructorWithSasCredentialSetsTransportTypeFromOptions()
        {
            var signature = new SharedAccessSignature("sb://fake.thing.com", "fakeKey", "fakeValue");
            var token     = new AzureSasCredential(signature.Value);
            var options   = new ServiceBusClientOptions {
                TransportType = ServiceBusTransportType.AmqpWebSockets
            };
            var client = new ServiceBusClient("fullyQualifiedNamespace", token, options);

            Assert.That(client.TransportType, Is.EqualTo(options.TransportType));
        }
コード例 #21
0
        /// <summary>
        ///   Initializes a new instance of the <see cref="SharedAccessCredential" /> class.
        /// </summary>
        ///
        /// <param name="sourceCredential">The <see cref="AzureNamedKeyCredential"/> to base signatures on.</param>
        /// <param name="signatureResource">The fully-qualified identifier for the resource to which this credential is intended to serve as authorization for.  This is also known as the "token audience" in some contexts.</param>
        ///
        public SharedAccessCredential(AzureNamedKeyCredential sourceCredential, string signatureResource)
        {
            Argument.AssertNotNull(sourceCredential, nameof(sourceCredential));
            Argument.AssertNotNullOrEmpty(signatureResource, nameof(signatureResource));

            _sourceKeyCredential = sourceCredential;
            _sourceSasCredential = null;

            var(name, key)         = sourceCredential;
            _sharedAccessSignature = new SharedAccessSignature(signatureResource, name, key);
        }
コード例 #22
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="PluggableCheckpointStoreEventProcessor{TPartition}"/> class.
 /// </summary>
 ///
 /// <param name="checkpointStore">The provider of checkpoint and ownership data for the processor.</param>
 /// <param name="eventBatchMaximumCount">The desired number of events to include in a batch to be processed.  This size is the maximum count in a batch; the actual count may be smaller, depending on whether events are available in the Event Hub.</param>
 /// <param name="consumerGroup">The name of the consumer group the processor is associated with.  Events are read in the context of this group.</param>
 /// <param name="fullyQualifiedNamespace">The fully qualified Event Hubs namespace to connect to.  This is likely to be similar to <c>{yournamespace}.servicebus.windows.net</c>.</param>
 /// <param name="eventHubName">The name of the specific Event Hub to associate the processor with.</param>
 /// <param name="credential">The shared signature credential to use for authorization.  Access controls may be specified by the Event Hubs namespace or the requested Event Hub, depending on Azure configuration.</param>
 /// <param name="options">The set of options to use for the processor.</param>
 ///
 /// <exception cref="ArgumentOutOfRangeException">Occurs when the requested <paramref name="eventBatchMaximumCount"/> is less than 1.</exception>
 ///
 protected PluggableCheckpointStoreEventProcessor(CheckpointStore checkpointStore,
                                                  int eventBatchMaximumCount,
                                                  string consumerGroup,
                                                  string fullyQualifiedNamespace,
                                                  string eventHubName,
                                                  AzureSasCredential credential,
                                                  EventProcessorOptions options = default) : base(eventBatchMaximumCount, consumerGroup, fullyQualifiedNamespace, eventHubName, credential, options)
 {
     Argument.AssertNotNull(checkpointStore, nameof(checkpointStore));
     _checkpointStore = checkpointStore;
 }
コード例 #23
0
        public AzureFileShareCrawler(
            string uri,
            string path,
            string sharedAccessSignature)
        {
            this.uri  = uri;
            this.path = path;

            this.sasCred     = new AzureSasCredential(sharedAccessSignature);
            this.shareClient = InitializeClient();
        }
コード例 #24
0
 /// <summary>
 /// Configures the <see cref="BlobServiceClient"/> using an authenticated service URI and a <see cref="Azure.AzureSasCredential"/>.
 /// </summary>
 public void ConfigureBlobServiceClient(Uri serviceUri, AzureSasCredential azureSasCredential)
 {
     if (serviceUri is null)
     {
         throw new ArgumentNullException(nameof(serviceUri));
     }
     if (azureSasCredential is null)
     {
         throw new ArgumentNullException(nameof(azureSasCredential));
     }
     CreateClient = () => Task.FromResult(new BlobServiceClient(serviceUri, azureSasCredential, ClientOptions));
 }
コード例 #25
0
        /// <summary>
        ///   Provides the invalid test cases for the constructor tests.
        /// </summary>
        ///
        public static IEnumerable <object[]> ConstructorSasCredentialArgumentInvalidCases()
        {
            var credential = new AzureSasCredential(new SharedAccessSignature("amqps://fake.namespace.com", "name", "value").Value);

            yield return(new object[] { null, credential });

            yield return(new object[] { "", credential });

            yield return(new object[] { "FakeNamespace", null });

            yield return(new object[] { "sb://fakenamspace.com", credential });
        }
        private ServiceBusAdministrationClient CreateSasTokenClient()
        {
            var properties = ServiceBusConnectionStringProperties.Parse(GetConnectionString());
            var resource   = ServiceBusAdministrationClient.BuildAudienceResource(TestEnvironment.FullyQualifiedNamespace);
            var signature  = new SharedAccessSignature(resource, properties.SharedAccessKeyName, properties.SharedAccessKey);
            var credential = new AzureSasCredential(signature.Value);

            return(InstrumentClient(
                       new ServiceBusAdministrationClient(
                           TestEnvironment.FullyQualifiedNamespace,
                           credential,
                           InstrumentClientOptions(new ServiceBusAdministrationClientOptions()))));
        }
コード例 #27
0
        /// <summary>
        ///   Provides the invalid test cases for the constructor tests.
        /// </summary>
        ///
        public static IEnumerable <object[]> ConstructorSasCredentialInvalidCases()
        {
            var signature  = new SharedAccessSignature("amqp://fake.resource.com", "fakeName", "fakeKey");
            var credential = new AzureSasCredential(signature.Value);

            yield return(new object[] { null, credential });

            yield return(new object[] { "", credential });

            yield return(new object[] { "FakeNamespace", null });

            yield return(new object[] { "sb://fakenamspace.com", credential });
        }
        public async Task ConnectionCanConnectToEventHubsUsingSasCredential()
        {
            await using (EventHubScope scope = await EventHubScope.CreateAsync(1))
            {
                var resource   = EventHubConnection.BuildConnectionSignatureAuthorizationResource(EventHubsTransportType.AmqpTcp, EventHubsTestEnvironment.Instance.FullyQualifiedNamespace, scope.EventHubName);
                var signature  = new SharedAccessSignature(resource, EventHubsTestEnvironment.Instance.SharedAccessKeyName, EventHubsTestEnvironment.Instance.SharedAccessKey);
                var credential = new AzureSasCredential(signature.Value);

                await using (var connection = new TestConnectionWithRetryPolicy(EventHubsTestEnvironment.Instance.FullyQualifiedNamespace, scope.EventHubName, credential))
                {
                    Assert.That(() => connection.GetPropertiesAsync(), Throws.Nothing);
                }
            }
        }
コード例 #29
0
        public void SasCredentialConstructorSetsDelegatedProperties()
        {
            var expectedIdentifier = "Test-Identifier";
            var expectedNamespace  = "testns.namespace.com";
            var expectedEventHub   = "testHub";
            var credential         = new AzureSasCredential(new SharedAccessSignature("sb://this.is.Fake/blah", "key", "value").Value);
            var options            = new EventHubBufferedProducerClientOptions {
                Identifier = expectedIdentifier
            };
            var producer = new EventHubBufferedProducerClient(expectedNamespace, expectedEventHub, credential, options);

            Assert.That(producer.Identifier, Is.EqualTo(expectedIdentifier), "The identifier should have been initialized.");
            Assert.That(producer.FullyQualifiedNamespace, Is.EqualTo(expectedNamespace), "The fully qualified namespace should have been initialized.");
            Assert.That(producer.EventHubName, Is.EqualTo(expectedEventHub), "The event hub name should have been initialized.");
        }
コード例 #30
0
        private DataLakeFileSystemClient GetClient(DataLakeSasTokenConnectionConfig connectionConfig)
        {
            // If we have an Azure Key Vault reference, we get the actual secret from there
            var secret = string.IsNullOrWhiteSpace(connectionConfig.KeyVault)
                ? connectionConfig.SasToken
                : _keyVaultHelper.GetKeyVaultSecretValue(connectionConfig.KeyVault, connectionConfig.SasToken);

            var cred = new AzureSasCredential(secret);

            _logger.LogInformation($"Using credential Type: {cred.GetType().Name}");

            return(new DataLakeFileSystemClient(new Uri(connectionConfig.BaseUrl), cred));

            throw new NotImplementedException();
        }