Example #1
0
        static async Task <LeafDevice> CreateWithCaCertAsync(
            string leafDeviceId,
            string parentId,
            CertificateAuthority ca,
            IotHub iotHub,
            ITransportSettings transport,
            string edgeHostname,
            CancellationToken token)
        {
            Device edge = await GetEdgeDeviceIdentityAsync(parentId, iotHub, token);

            Device leaf = new Device(leafDeviceId)
            {
                Authentication = new AuthenticationMechanism
                {
                    Type = AuthenticationType.CertificateAuthority
                },
                Scope = edge.Scope
            };

            leaf = await iotHub.CreateDeviceIdentityAsync(leaf, token);

            return(await DeleteIdentityIfFailedAsync(
                       leaf,
                       iotHub,
                       token,
                       async() =>
            {
                LeafCertificates certFiles = await ca.GenerateLeafCertificatesAsync(leafDeviceId, token);

                (X509Certificate2 leafCert, IEnumerable <X509Certificate2> trustedCerts) =
                    CertificateHelper.GetServerCertificateAndChainFromFile(certFiles.CertificatePath, certFiles.KeyPath);
                // .NET runtime requires that we install the chain of CA certs, otherwise it can't
                // provide them to a server during authentication.
                OsPlatform.Current.InstallTrustedCertificates(trustedCerts);

                return await CreateLeafDeviceAsync(
                    leaf,
                    () => DeviceClient.Create(
                        iotHub.Hostname,
                        edgeHostname,
                        new DeviceAuthenticationWithX509Certificate(leaf.Id, leafCert),
                        new[] { transport }),
                    iotHub,
                    token);
            }));