Exemplo n.º 1
0
        private static async Task <SubscriberHost> SetupSubscriberHostAsync(CancellationTokenSource lifetimeCts)
        {
            using var securityDaemonClient = new SecurityDaemonClient();

            // get server certificate to configure with
            Console.WriteLine($"Configure server certificate");
            (X509Certificate2 serverCert, X509Certificate2[] certChain) =
                await securityDaemonClient.GetServerCertificateAsync().ConfigureAwait(false);

            CertificateHelper.ImportCertificate(serverCert);
            CertificateHelper.ImportIntermediateCAs(serverCert);
            CertificateHelper.ImportIntermediateCAs(certChain);

            // Configure client trust bundle
            Console.WriteLine($"Configure client trust bundle");
            var trustBundle = await securityDaemonClient.GetTrustBundleAsync();

            CertificateHelper.ImportIntermediateCAs(trustBundle);

            // start subscriber webhost
            SubscriberHost host = new SubscriberHost(serverCert, lifetimeCts);
            await host.StartAsync().ConfigureAwait(false);

            return(host);
        }
Exemplo n.º 2
0
        private static async Task <EventGridEdgeClient> GetEventGridClientAsync(GridConfiguration gridConfig)
        {
            string[] urlTokens = gridConfig.Url.Split(":");
            if (urlTokens.Length != 3)
            {
                throw new Exception($"URL should be of the form '<protocol>://<moduleName>:<portNo>' ");
            }

            string baseUrl = urlTokens[0] + ":" + urlTokens[1];
            int    port    = int.Parse(urlTokens[2], CultureInfo.InvariantCulture);

            if (gridConfig.ClientAuth.Source.Equals("IoTEdge", StringComparison.OrdinalIgnoreCase))
            {
                SecurityDaemonClient iotSecurity = new SecurityDaemonClient();
                (X509Certificate2 identityCertificate, IEnumerable <X509Certificate2> chain) = await iotSecurity.GetIdentityCertificateAsync();

                return(new EventGridEdgeClient(baseUrl, port, new CustomHttpClientFactory(chain.First(), identityCertificate)));
            }
            else if (gridConfig.ClientAuth.Source.Equals("BearerToken", StringComparison.OrdinalIgnoreCase))
            {
                EventGridEdgeClient egClient = new EventGridEdgeClient(baseUrl, port);

                HttpRequestHeaders defaultMgmtRequestHeaders = egClient.HttpClient.DefaultRequestHeaders;
                defaultMgmtRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{gridConfig.ClientAuth.Token1}");

                HttpRequestHeaders defaultRuntimeRequestHeaders = egClient.HttpClient.DefaultRequestHeaders;
                defaultRuntimeRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", $"{gridConfig.ClientAuth.Token1}");
            }

            throw new Exception("Cannot create eventgrid client!");
        }
Exemplo n.º 3
0
        private static async Task <EventGridEdgeClient> GetEventGridClientAsync(GridConfiguration gridConfig)
        {
            using var securityDaemonClient = new SecurityDaemonClient();

            // get the client certificate to use when communicating with eventgrid
            (X509Certificate2 clientCertificate, X509Certificate2[] chain) = await securityDaemonClient.GetIdentityCertificateAsync().ConfigureAwait(false);

            Console.WriteLine($"Client Certificate issue is valid from {clientCertificate.NotBefore}, {clientCertificate.NotAfter}");
            string[] urlTokens = gridConfig.Url.Split(":");
            if (urlTokens.Length != 3)
            {
                throw new Exception($"URL should be of the form '<protocol>://<moduleName>:<portNo>' ");
            }

            string baseUrl = urlTokens[0] + ":" + urlTokens[1];
            int    port    = int.Parse(urlTokens[2], CultureInfo.InvariantCulture);

            return(new EventGridEdgeClient(baseUrl, port, new CustomHttpClientFactory(chain[0], clientCertificate)));
        }
Exemplo n.º 4
0
        public async Task Init(CancellationTokenSource cancellationTokenSource)
        {
            var tokenHelper = new SecurityDaemonClient();

            while (!cancellationTokenSource.IsCancellationRequested)
            {
                try
                {
                    Console.WriteLine($"tokenHelper: '{tokenHelper.ToString()}'");
                    var token = tokenHelper.GetModuleToken(3600).Result;
                    Console.WriteLine($"Token: '{token}'");
                    var tokenAuthentication = new ModuleAuthenticationWithToken(tokenHelper.DeviceId, tokenHelper.ModuleId, token);

                    var transportType             = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
                    ITransportSettings[] settings = { transportType };
                    using (ModuleClient moduleClient = ModuleClient.Create(tokenHelper.IotHubHostName, tokenAuthentication, settings))
                    {
                        if (moduleClient == null)
                        {
                            Console.WriteLine("Failed to create ModuleClient!");
                            throw new InvalidOperationException("Failed to create ModuleClient");
                        }
                        moduleClient.SetConnectionStatusChangesHandler((ConnectionStatus status, ConnectionStatusChangeReason reason) =>
                        {
                            if (reason == ConnectionStatusChangeReason.Bad_Credential)
                            {
                                Init(cancellationTokenSource).Wait();
                            }
                        });

                        Console.WriteLine($"Starting DeviceStreamSample on '{_hostName}:{_port}'");
                        await RunSampleAsync(moduleClient, true, cancellationTokenSource);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"{DateTime.UtcNow} - Got an exception: {ex.ToString()}");
                    Console.WriteLine("Waiting 1 minute and trying again...");
                    await Task.Delay(TimeSpan.FromMinutes(1));
                }
            }
        }