You can make use of the device provisioning service - DPS. The DPS is another service whose purpose is to identify your device, and in case that the device identification is recognized by the DPS, the DPS will create an identity in your IoT Hub.
You set the DPS in a way that you create either individual enrollment(for individual device onboarding) or a group enrollment(for a group of the devices, typically if you use certificates or shared access key authentication type).
Enrollments typically contain an identification type that the device should present, and IoT Hub to which the device with the presented identification should be assigned.
The typical flow is that the device reaches out to the DPS with some public identification(certificate chain, TPM registration id, or SAS key). Then internally, the DPS can challenge the device(proof-of-possesion in case of CA certificates), and if the device successfully solves the challenge, that means that the device contains a specific secret(private key in case of CA certs) that identifies that device, so the DPS will create the device identity to the assigned hub in that specific enrollment. This process is called attestation.
As a result, on the device side, you receive at least the IoT Hub endpoint, and the device Id which you use to communicate with the IoT Hub.
Below are the code snippets of how you can do this with CA certificates and C#:
var certificate = new X509Certificate2(leafCertificatePath, leafCertificatePassword);
using (var security = new SecurityProviderX509Certificate(certificate))
using (var transport = new ProvisioningTransportHandlerMqtt(TransportFallbackType.TcpOnly))
{
ProvisioningDeviceClient provClient =
ProvisioningDeviceClient.Create(GlobalDeviceEndpoint, dpsScope, security, transport);
var deviceAuthentication = await GetDeviceRegistrationResultAsync(provClient, security);
var auth = new DeviceAuthenticationWithX509Certificate(deviceAuthentication.DeviceId, security.GetAuthenticationCertificate());
var deviceClient = DeviceClient.Create(hostname: deviceAuthentication.AssignedHub,
authenticationMethod: auth,
transportType: TransportType.Mqtt);
if (deviceClient == null)
{
Console.WriteLine("Failed to create DeviceClient!");
}
else
{
SendEvents(deviceClient, MESSAGE_COUNT).Wait();
}
}
Method for getting the device registration result from the DPS:
static async Task<DeviceRegistrationResult> GetDeviceRegistrationResultAsync(ProvisioningDeviceClient provClient, SecurityProviderX509 security)
{
DeviceRegistrationResult result = await provClient.RegisterAsync().ConfigureAwait(false);
if (result.Status != ProvisioningRegistrationStatusType.Assigned)
{
throw new Exception("Device not assigned");
}
return result;
}
Official example from MSFT you can find here
Here is how you can create and verify certificates with IoT Hub and DPS.