如何使用 ClientSecretCredential 即 ClientId、TenantId、ClientSecret 创建 Microsoft.Azure.Devices.ServiceClient 实例

问题描述 投票:0回答:1

如何使用 ClientSecretCredential 即 ClientId、TenantId、ClientSecret 创建 Microsoft.Azure.Devices.ServiceClient 实例

我们可以制作 AzureSasCredential 或 TokenCredential 以便我可以使用 Create 方法!帮助赞赏!

或者如果我们知道ClientSecretCredential,我们如何获取SharedAccessKey,SharedAccessKeyName

ServiceClient.CreateFromConnectionString(connString) 这适用于 SharedAccessKey 等,但这不是有意的!

我可以获得访问令牌,但这不能用于

var clientCred = new ClientSecretCredential(message.TenantId, message.ClientId, message.ClientSecret);
var tocken2 = await clientCred.GetTokenAsync(new TokenRequestContext(new string[] { scope }))
azure azure-iot-hub azure-service-principal
1个回答
0
投票

下面的代码使用了带有

Microsoft.Azure.Devices.ServiceClient
ClientSecretCredential
实例,它使用了
ClientId
TenantId
ClientSecret

使用

ServiceClient
HostName
创建一个
ClientSecretCredential
实例。

  • 使用此链接通过 Microsoft Entra ID
  • 控制对 IoT 中心的访问
  • ServiceClient
    的代码取自GitHub

            string hostName = "your-iot-hub.azure-devices.net";  // Your IoT Hub host name
            string deviceId = "your-device-id";  // Your target device ID
            string clientId = "your-client-id";  // Your Azure AD application client ID
            string tenantId = "your-tenant-id";  // Your Azure AD tenant ID
            string clientSecret = "your-client-secret";  // Your Azure AD application client secret
            
           instance using your client ID, tenant ID, and client secret
            ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret);
            
            // Create a ServiceClient instance using the hostname and the ClientSecretCredential instance
            // You can specify the transport type (e.g., Amqp or Amqp_WebSocket_Only)
            TransportType transportType = TransportType.Amqp;
            ServiceClient serviceClient = ServiceClient.Create(hostName, clientSecretCredential, transportType);
            
            // Use the ServiceClient instance to communicate with the IoT Hub
            // Example: Send a message to a device
            await serviceClient.OpenAsync();
            Console.WriteLine("Connection opened to IoT Hub.");

            string messageText = "Hello, Cloud!";
            Message cloudToDeviceMessage = new Message(Encoding.UTF8.GetBytes(messageText));

            // Send the message to the device
            await serviceClient.SendAsync(deviceId, cloudToDeviceMessage);
            Console.WriteLine($"Message sent to device {deviceId}: {messageText}");

            
            await serviceClient.CloseAsync();

输出:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.