1

I am receiving the verbose error "CONNECT failed: RefusedNotAuthorized" when attempting to connect to Azure IOT Hub with thumbprint authorization. I am able to connect without issue when creating a device with symmetric key authorization. I've struggled with various google searches all weekend and am at a lose as to how to proceed with debugging.

I am successfully registering a device with my Azure IOT Hub, using the following code:

        ...

        var certificate = certificateHelper.CreateSelfSignedCertificate(userRequest.DeviceID.ToString());

        // connect to iot hub
        var registryManager = RegistryManager.CreateFromConnectionString("[My Connection String]");

        // define device
        Device iotDevice = new Device(userRequest.DeviceID.ToString());

        iotDevice.Authentication = new AuthenticationMechanism()
        {
            Type = AuthenticationType.SelfSigned,
            X509Thumbprint = new X509Thumbprint()
            {
                PrimaryThumbprint = certificate.Thumbprint,
                SecondaryThumbprint = certificate.Thumbprint
            }
        };

        // register
        try
        {
            iotDevice = await registryManager.AddDeviceAsync(iotDevice);
        }
        catch (DeviceAlreadyExistsException)
        {

        ...

I am creating the self signed certificates with the following code:

    public X509Certificate2 CreateSelfSignedCertificate(string subjectName)
    {
        var ecdsa = ECDsa.Create(); // generate asymmetric key pair
        var req = new CertificateRequest("CN=" + subjectName, ecdsa, HashAlgorithmName.SHA256);
        return req.CreateSelfSigned(DateTimeOffset.Now, DateTimeOffset.Now.AddYears(1));
    }

And finally I am trying to connect to the IOT hub from the following code:

        X509Certificate2 cert = new X509Certificate2(Convert.FromBase64String(device.Certificate));

        var deviceAuthentication = new DeviceAuthenticationWithX509Certificate(device.TestDeviceID.ToString(), cert);

        IotHub = DeviceClient.Create(_hostname, deviceAuthentication, TransportType.Mqtt);

        IotHub.OpenAsync().Wait();

If there is something simple that is incorrect great, I would love to know. But what I'm really interested in is how I can debug this. I assume there are logs for the IOT server that will give me more information about why it believes that the device is unauthorized. Where are they? Do I query the hub for them or set up something in the portal? I've spent all weekend banging my head against a generic error and while I've learned a lot more about certificates and the hub itself, I still get the error.

Steve Reed
  • 11
  • 3
  • You can use metrics and logs at IoTHub Level as described here: https://learn.microsoft.com/en-us/azure/iot-hub/tutorial-use-metrics-and-diags – asergaz Jun 23 '21 at 15:10

0 Answers0