C# IoT Device SDK, IotHubUnauthorizedAccess only when using X.509 Cert to GetFileUploadSasUriAsync

huangapple go评论87阅读模式
英文:

C# IoT Device SDK, IotHubUnauthorizedAccess only when using X.509 Cert to GetFileUploadSasUriAsync

问题

I'm putting together a test harness for IoT as an internal reference for our company.
我正在组建一个IoT的测试工具,作为我们公司的内部参考。

I can switch between SymmetricKey and X509 Certs, provision either using DPS and run tests against the endpoints we're interested in.
我可以在SymmetricKey和X509证书之间切换,使用DPS提供其中之一,并对我们感兴趣的端点运行测试。

As I come to test File Upload functionality, when using SymmetricKey, I can request and post a file to the storage account. Using exactly the same method to do the same with X509 cert as the authentication method, I encounter the issue below.
当我要测试文件上传功能时,使用SymmetricKey,我可以请求并上传文件到存储账户。但当我使用X509证书作为认证方式时,使用完全相同的方法进行操作时,我遇到了以下问题。

When using X509 using the same 'DeviceClient' instance, I can send data, update and recall twins, Send C2D messages and invoke methods. Only GetFileUploadSasUriAsync encounters this issue and I'm stumped.
当使用相同的“DeviceClient”实例使用X509时,我可以发送数据,更新和回收双生对象,发送C2D消息并调用方法。只有GetFileUploadSasUriAsync方法遇到了这个问题,我感到困惑。

Line which generates the error:
生成错误的代码行:

"FileUploadSasUriResponse sasUri = await
_deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest, CancellationToken.None);"

What am I doing wrong?
我做错了什么?

CODE
代码

InitialiseIoTClient
初始化IoT客户端

var certPath = AppDomain.CurrentDomain.BaseDirectory + storedConfig.CertName;
var certificate = new X509Certificate2(certPath, storedConfig.CertPassword);
var security = new SecurityProviderX509Certificate(certificate);
var auth = new DeviceAuthenticationWithX509Certificate(storedConfig.DeviceName, certificate);
IoTDeviceClient = DeviceClient.Create(storedConfig.AssignedIoTHub, auth, TransportType.Mqtt);
IoTDeviceClient.SetRetryPolicy(new ExponentialBackoff(5, new TimeSpan(0, 1, 30), new TimeSpan(0, 1, 30), new TimeSpan(0, 1, 15)));
IoTDeviceClient.OpenAsync().Wait();

FileOperations Class
文件操作类

public class FileOperations
{
readonly DeviceClient _deviceClient;

public static LocalConfigStore ConfigStore = new LocalConfigStore();

/// <summary>
/// Load the client and start listening for file upload notifications
/// </summary>
internal FileOperations()
{
    _deviceClient = Program.IoTDeviceClient;

    ReceiveFileUploadNotificationAsync();
}

/// <summary>
///  This method is used to upload a file to the IoT Hub
/// </summary>
public async void UploadFile()
{
    // Generate a large file to upload
    var commonOps = new Utils.Common();
    var testFilePath = commonOps.GenerateLargeFile();

    // Create stream
    using var fileStreamSource = new FileStream(testFilePath, FileMode.Open);
    var fileName = Path.GetFileName(testFilePath);

    var fileUploadTime = Stopwatch.StartNew();

    // Get the SAS URI for the file upload
    var fileUploadSasUriRequest = new FileUploadSasUriRequest
    {
        BlobName = fileName
    };
    FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest, CancellationToken.None);
    Uri uploadUri = sasUri.GetBlobUri();

    Console.WriteLine($"Uploading file {fileName} to {uploadUri}.");

    // Upload the file to blob storage
    var blockBlobClient = new BlockBlobClient(uploadUri);
    await blockBlobClient.UploadAsync(fileStreamSource, new BlobUploadOptions());

    // Notify IoT Hub that the file upload is complete
    var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
    {
        // Mandatory. Must be the same value as the correlation id returned in the sas uri response
        CorrelationId = sasUri.CorrelationId,

        // Mandatory. Will be present when service client receives this file upload notification
        IsSuccess = true,

        // Optional, user defined status code. Will be present when service client receives this file upload notification
        StatusCode = 200,

        // Optional, user-defined status description. Will be present when service client receives this file upload notification
        StatusDescription = "Success"
    };

    // Notify IoT Hub that the file upload is complete
    await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);

    fileUploadTime.Stop();

    Console.WriteLine("File upload completed successfully.");

    Console.WriteLine($"Time to upload file: {fileUploadTime.Elapsed}.");

    Console.WriteLine("Deleting Test File.");

    fileStreamSource.Dispose();

    File.Delete(testFilePath);

    Console.WriteLine("press enter to continue.");

}

/// <summary>
///  This method is used to receive file upload notifications
/// </summary>
private async void ReceiveFileUploadNotificationAsync()
{
    var connectionString = ConfigurationManager.AppSettings["ConnectionStringIotHubOwner"];

    // Create service client to receive file upload notifications
    ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

    // Get file upload notification receiver
    var notificationReceiver = serviceClient.GetFileNotificationReceiver();

    Console.WriteLine("\nReceiving file upload notification from service");
    while (true)
    {
        // Wait for file upload notification
        var fileUploadNotification = await notificationReceiver.ReceiveAsync();
        if (fileUploadNotification == null) continue;
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine("Received file upload notification: {0}", string.Join(", ", fileUploadNotification.BlobName));
        Console.ResetColor();
        await notificationReceiver.CompleteAsync(fileUploadNotification);
    }
}

}
错误
错误

{"Message":"ErrorCode:IotHubUnauthorizedAccess;Unauthorized","ExceptionMessage":"Tracking ID:2d210xxxxxxxxe3afdc-G:0-TimeStamp:08/04/2023 15:48:25"}

at Microsoft.Azure.Devices.Client.Transport.HttpClientHelper.d__22.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.Devices.Client.Transport.HttpClientHelper.d__182.MoveNext() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.Devices.Client.Transport.HttpTransportHandler.<GetFileUploadSasUriAsync>d__15.MoveNext() at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at RemoteIoTDeviceConsoleApp.Class.Data.FileOperations.<

英文:

I'm putting together a test harness for IoT as an internal reference for our company.

I can switch between SymmetricKey and X509 Certs, provision either using DPS and run tests against the endpoints we're interested in.

As I come to test File Upload functionality, when using SymmetricKey, I can request and post a file to the storage account. Using exactly the same method to do the same with X509 cert as the authentication method, I encounter the issue below.

When using X509 using the same 'DeviceClient' instance, I can send data, update and recall twins, Send C2D messages and invoke methods. Only GetFileUploadSasUriAsync encounters this issue and I'm stumped.

Line which generates the error:

> "FileUploadSasUriResponse sasUri = await
> _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest, CancellationToken.None);"

What am I doing wrong?

CODE

InitialiseIoTClient

var certPath = AppDomain.CurrentDomain.BaseDirectory + storedConfig.CertName;

Console.WriteLine($&quot;Loading the certificate...&quot;);
using X509Certificate2 certificate = new X509Certificate2(certPath, storedConfig.CertPassword);
using var security = new SecurityProviderX509Certificate(certificate);
using var auth = new DeviceAuthenticationWithX509Certificate(storedConfig.DeviceName, certificate);
IoTDeviceClient = DeviceClient.Create(storedConfig.AssignedIoTHub, auth, TransportType.Mqtt);
IoTDeviceClient.SetRetryPolicy(new ExponentialBackoff(5, new TimeSpan(0, 1, 30), new TimeSpan(0, 1, 30), new TimeSpan(0, 1, 15)));
IoTDeviceClient.OpenAsync().Wait();

FileOperations Class

public class FileOperations
    {
        readonly DeviceClient _deviceClient;

        public static LocalConfigStore ConfigStore = new LocalConfigStore();

        /// &lt;summary&gt;
        /// Load the client and start listening for file upload notifications
        /// &lt;/summary&gt;
        internal FileOperations()
        {
            _deviceClient = Program.IoTDeviceClient;

            ReceiveFileUploadNotificationAsync();
        }

        /// &lt;summary&gt;
        ///  This method is used to upload a file to the IoT Hub
        /// &lt;/summary&gt;
        public async void UploadFile()
        {
            // Generate a large file to upload
            var commonOps = new Utils.Common();
            var testFilePath = commonOps.GenerateLargeFile();

            // Create stream
            using var fileStreamSource = new FileStream(testFilePath, FileMode.Open);
            var fileName = Path.GetFileName(testFilePath);

            var fileUploadTime = Stopwatch.StartNew();

            // Get the SAS URI for the file upload
            var fileUploadSasUriRequest = new FileUploadSasUriRequest
            {
                BlobName = fileName
            };
            FileUploadSasUriResponse sasUri = await _deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest, CancellationToken.None);
            Uri uploadUri = sasUri.GetBlobUri();

            Console.WriteLine($&quot;Uploading file {fileName} to {uploadUri}.&quot;);

            // Upload the file to blob storage
            var blockBlobClient = new BlockBlobClient(uploadUri);
            await blockBlobClient.UploadAsync(fileStreamSource, new BlobUploadOptions());

            // Notify IoT Hub that the file upload is complete
            var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
            {
                // Mandatory. Must be the same value as the correlation id returned in the sas uri response
                CorrelationId = sasUri.CorrelationId,

                // Mandatory. Will be present when service client receives this file upload notification
                IsSuccess = true,

                // Optional, user defined status code. Will be present when service client receives this file upload notification
                StatusCode = 200,

                // Optional, user-defined status description. Will be present when service client receives this file upload notification
                StatusDescription = &quot;Success&quot;
            };

            // Notify IoT Hub that the file upload is complete
            await _deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);

            fileUploadTime.Stop();

            Console.WriteLine($&quot;File upload completed successfully.&quot;);

            Console.WriteLine($&quot;Time to upload file: {fileUploadTime.Elapsed}.&quot;);

            Console.WriteLine($&quot;Deleting Test File.&quot;);
            
            fileStreamSource.Dispose();

            File.Delete(testFilePath);

            Console.WriteLine(&quot;press enter to continue.&quot;);
    
        }

        /// &lt;summary&gt;
        ///  This method is used to receive file upload notifications
        /// &lt;/summary&gt;
        private async void ReceiveFileUploadNotificationAsync()
        {
            var connectionString = ConfigurationManager.AppSettings[&quot;ConnectionStringIotHubOwner&quot;];

            // Create service client to receive file upload notifications
            ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

            // Get file upload notification receiver
            var notificationReceiver = serviceClient.GetFileNotificationReceiver();

            Console.WriteLine(&quot;\nReceiving file upload notification from service&quot;);
            while (true)
            {
                // Wait for file upload notification
                var fileUploadNotification = await notificationReceiver.ReceiveAsync();
                if (fileUploadNotification == null) continue;
                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine(&quot;Received file upload notification: {0}&quot;, string.Join(&quot;, &quot;, fileUploadNotification.BlobName));
                Console.ResetColor();
                await notificationReceiver.CompleteAsync(fileUploadNotification);
            }
        }
        
    }

ERROR

{&quot;Message&quot;:&quot;ErrorCode:IotHubUnauthorizedAccess;Unauthorized&quot;,&quot;ExceptionMessage&quot;:&quot;Tracking ID:2d210xxxxxxxxe3afdc-G:0-TimeStamp:08/04/2023 15:48:25&quot;}

   at Microsoft.Azure.Devices.Client.Transport.HttpClientHelper.&lt;ExecuteAsync&gt;d__22.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Devices.Client.Transport.HttpClientHelper.&lt;PostAsync&gt;d__18`2.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.Azure.Devices.Client.Transport.HttpTransportHandler.&lt;GetFileUploadSasUriAsync&gt;d__15.MoveNext()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at RemoteIoTDeviceConsoleApp.Class.Data.FileOperations.&lt;UploadFile&gt;d__3.MoveNext() in E:\zzzz\xxxx\xxx\xxx\Class\Data\FileOperations.cs:line 53

答案1

得分: 1

错误消息"ErrorCode:IotHubUnauthorizedAccess;Unauthorized" 表明在尝试使用 X.509 证书进行身份验证时,您的设备访问 IoT Hub 服务时遇到了授权问题。以下是使用 X509 证书进行文件上传到 IoT Hub 的示例代码。

  • 使用证书:
var cert = new X509Certificate2("C:\\Tools\\cert\\MyCert.cer");
var auth = new DeviceAuthenticationWithX509Certificate("mydevice", cert);

var DClnt = DeviceClient.Create("HostName", auth);
  • 使用指纹:
private const string CertificateThumbprint = "E9DB5307C576E23009";
private const string IotHubHostName = "sampath.azure-devices.net";
private const string DeviceId = "fa";
private const string FilePath = "C:/Users/Hello.js";

static async Task Main(string[] args)
{
    try
    {
        var auth = new DeviceAuthenticationWithX509Certificate(DeviceId, GetCertificateByThumbprint(CertificateThumbprint));
        var deviceClient = DeviceClient.Create(IotHubHostName, auth, TransportType.Http1);

        await SendToBlobSample(deviceClient);
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0}\n", ex.Message);
        if (ex.InnerException != null)
        {
            Console.WriteLine(ex.InnerException.Message + "\n");
        }
    }
}

// 其余代码未翻译,仅提供示例部分的翻译

上述代码示例演示了如何使用 X.509 证书进行 IoT Hub 认证并上传文件到 Azure Blob 存储。

英文:

The error message "ErrorCode:IotHubUnauthorizedAccess;Unauthorized" you're encountering indicates an authorization issue when trying to access the IoT Hub service from your device using X.509 certificate authentication.Giving you an example sample of File Upload in IoT Hub using X509 Certs with GetFileUploadSasUriAsync.

  • With Certification:
var cert = new X509Certificate2(&quot;C:\\Tools\\cert\\MyCert.cer&quot;);
var auth = new DeviceAuthenticationWithX509Certificate(&quot;mydevice&quot;, cert);

var DClnt = DeviceClient.Create(&quot;HostName&quot;, auth);
  • With Thumbprint:
 private const string CertificateThumbprint = &quot;E9DB5307C576E23009&quot;;
        private const string IotHubHostName = &quot;sampath.azure-devices.net&quot;;
        private const string DeviceId = &quot;fa&quot;;
        private const string FilePath = &quot;C:/Users/Hello.js&quot;;

        static async Task Main(string[] args)
        {
            try
            {
                var auth = new DeviceAuthenticationWithX509Certificate(DeviceId, GetCertificateByThumbprint(CertificateThumbprint));
                var deviceClient = DeviceClient.Create(IotHubHostName, auth, TransportType.Http1);

                await SendToBlobSample(deviceClient);
            }
            catch (Exception ex)
            {
                Console.WriteLine(&quot;{0}\n&quot;, ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.Message + &quot;\n&quot;);
                }
            }
        }

        static async Task SendToBlobSample(DeviceClient deviceClient)
        {
            var fileStreamSource = new FileStream(FilePath, FileMode.Open);
            var fileName = Path.GetFileName(FilePath);

            Console.WriteLine(&quot;Uploading File: {0}&quot;, fileName);

            var watch = System.Diagnostics.Stopwatch.StartNew();

            var fileUploadSasUriRequest = new FileUploadSasUriRequest
            {
                BlobName = fileName
            };

            FileUploadSasUriResponse sasUri = await deviceClient.GetFileUploadSasUriAsync(fileUploadSasUriRequest);
            Uri uploadUri = sasUri.GetBlobUri();
            var blockBlobClient = new BlockBlobClient(uploadUri);
            await blockBlobClient.UploadAsync(fileStreamSource, new BlobUploadOptions());

            watch.Stop();

            Console.WriteLine(&quot;Time to upload file: {0}ms\n&quot;, watch.ElapsedMilliseconds);
            Console.WriteLine(&quot;File uploaded to Azure Blob Storage: {0}&quot;, fileName);

            var successfulFileUploadCompletionNotification = new FileUploadCompletionNotification
            {
                CorrelationId = sasUri.CorrelationId,
                IsSuccess = true,
                StatusCode = 200,
                StatusDescription = &quot;Success&quot;
            };

            await deviceClient.CompleteFileUploadAsync(successfulFileUploadCompletionNotification);
        }

        static X509Certificate2 GetCertificateByThumbprint(string thumbprint)
        {
            using (X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser))
            {
                store.Open(OpenFlags.ReadOnly);
                var certificates = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
                if (certificates.Count &gt; 0)
                {
                    return certificates[0];
                }
                else
                {
                    throw new Exception(&quot;Certificate not found.&quot;);
                }
            }
        }

C# IoT Device SDK, IotHubUnauthorizedAccess only when using X.509 Cert to GetFileUploadSasUriAsync

C# IoT Device SDK, IotHubUnauthorizedAccess only when using X.509 Cert to GetFileUploadSasUriAsync

huangapple
  • 本文由 发表于 2023年8月5日 00:05:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76837562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定