Skip to content

Instantly share code, notes, and snippets.

@danigian
Created February 14, 2020 09:00
Show Gist options
  • Save danigian/df730a472e474088b19713f4526ef0d4 to your computer and use it in GitHub Desktop.
Save danigian/df730a472e474088b19713f4526ef0d4 to your computer and use it in GitHub Desktop.
IoT Hub Connection string retrieval with Managed Identities
static async Task GetIoTHubResource()
{
var azureServiceTokenProvider = new Microsoft.Azure.Services.AppAuthentication.AzureServiceTokenProvider();
var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
var tokenCredentials = new Microsoft.Rest.TokenCredentials(accessToken);
var iotHubClient = new Microsoft.Azure.Management.IotHub.IotHubClient(tokenCredentials);
iotHubClient.SubscriptionId = subscriptionId;
var iotHubDescription = await iotHubClient.IotHubResource.GetAsync(resourceGroupName,iotHubName);
//You can replace iothubowner with the name of your Shared access policy
var keys = await iotHubClient.IotHubResource.GetKeysForKeyNameAsync(resourceGroupName,iotHubName,"iothubowner");
Console.WriteLine($"Primary key for {iotHubDescription.Name} located in {iotHubDescription.Location}: {keys.PrimaryKey}");
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Management.IotHub" Version="2.1.1" />
<PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.4.0" />
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="3.0.3" />
</ItemGroup>
</Project>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment