Migrate an application to use passwordless connections with Azure Event Hubs
Article
Application requests to Azure services must be authenticated using configurations such as account access keys or passwordless connections. However, you should prioritize passwordless connections in your applications when possible. Traditional authentication methods that use passwords or secret keys create security risks and complications. Visit the passwordless connections for Azure services hub to learn more about the advantages of moving to passwordless connections.
The following tutorial explains how to migrate an existing application to connect using passwordless connections. These same migration steps should apply whether you're using access keys, connection strings, or another secrets-based approach.
Configure your local development environment
Passwordless connections can be configured to work for both local and Azure-hosted environments. In this section, you apply configurations to allow individual users to authenticate to Azure Event Hubs for local development.
Assign user roles
When developing locally, make sure that the user account that is accessing Azure Event Hubs has the correct permissions. You'll need the Azure Event Hubs Data Receiver and Azure Event Hubs Data Sender roles to read and write message data. To assign yourself this role, you'll need to be assigned the User Access Administrator role, or another role that includes the Microsoft.Authorization/roleAssignments/write action. You can assign Azure RBAC roles to a user using the Azure portal, Azure CLI, or Azure PowerShell. Learn more about the available scopes for role assignments on the scope overview page.
The following example assigns the Azure Event Hubs Data Sender and Azure Event Hubs Data Receiver roles to your user account. These role grants read and write access to event hub messages.
In the Azure portal, locate your event hub using the main search bar or left navigation.
On the event hub overview page, select Access control (IAM) from the left-hand menu.
On the Access control (IAM) page, select the Role assignments tab.
Select + Add from the top menu and then Add role assignment from the resulting drop-down menu.
Use the search box to filter the results to the desired role. For this example, search for Azure Event Hubs Data Sender and select the matching result and then choose Next.
Under Assign access to, select User, group, or service principal, and then choose + Select members.
In the dialog, search for your Microsoft Entra username (usually your user@domain email address) and then choose Select at the bottom of the dialog.
Select Review + assign to go to the final page, and then Review + assign again to complete the process.
Repeat these steps for the Azure Event Hubs Data Receiver role to allow the account to send and receive messages.
To assign a role at the resource level using the Azure CLI, you first must retrieve the resource ID using the az eventhubs eventhub show command. You can filter the output properties using the --query parameter.
az eventhubs eventhub show \
--resource-group '<your-resource-group-name>' \
--namespace-name '<your-event-hubs-namespace>' \
--name '<your-event-hub-name>' \
--query id
Copy the output Id from the preceding command. You can then assign roles using the az role command of the Azure CLI.
az role assignment create --assignee "<user@domain>" \
--role "Azure Event Hubs Data Receiver" \
--scope "<your-resource-id>"
az role assignment create --assignee "<user@domain>" \
--role "Azure Event Hubs Data Sender" \
--scope "<your-resource-id>"
To assign a role at the resource level using Azure PowerShell, you first must retrieve the resource ID using the Get-AzResource command.
In most cases, it will take a minute or two for the role assignment to propagate in Azure, but in rare cases it may take up to eight minutes. If you receive authentication errors when you first run your code, wait a few moments and try again.
Sign-in to Azure locally
For local development, make sure you're authenticated with the same Microsoft Entra account you assigned the role to. You can authenticate via popular development tools, such as the Azure CLI or Azure PowerShell. The development tools with which you can authenticate vary across languages.
Sign-in to Azure through the Azure CLI using the following command:
az login
Select the Sign in button in the top right of Visual Studio.
Sign-in using the Microsoft Entra account you assigned a role to previously.
You will need to install the Azure CLI to work with DefaultAzureCredential through Visual Studio Code.
On the main menu of Visual Studio Code, navigate to Terminal > New Terminal.
Sign-in to Azure through the Azure CLI using the following command:
az login
Sign-in to Azure using PowerShell via the following command:
Connect-AzAccount
Update the application code to use passwordless connections
The Azure Identity client library, for each of the following ecosystems, provides a DefaultAzureCredential class that handles passwordless authentication to Azure:
DefaultAzureCredential supports multiple authentication methods. The method to use is determined at runtime. This approach enables your app to use different authentication methods in different environments (local vs. production) without implementing environment-specific code. See the preceding links for the order and locations in which DefaultAzureCredential looks for credentials.
To use DefaultAzureCredential in a .NET application, install the Azure.Identity package:
dotnet add package Azure.Identity
At the top of your file, add the following code:
using Azure.Identity;
Identify the locations in your code that create an EventHubProducerClient or EventProcessorClient object to connect to Azure Event Hubs. Update your code to match the following example:
Identify the locations in your code that create a ProducerClient or ConsumerClient instance to connect to Azure Event Hubs. Update your code to match the following example:
Identify the locations in your code that create an EventHubProducerClient or EventProcessorClient object to connect to Azure Event Hubs. Update your code to match the following example:
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
.build();
String eventHubNamespace = "https://" + namespace + ".servicebus.windows.net";
// Event Hubs producer
EventHubProducerClient producerClient = new EventHubClientBuilder()
.credential(eventHubNamespace, eventHubName, credential)
.buildProducerClient();
// Event Hubs processor
EventProcessorClient processorClient = new EventProcessorClientBuilder()
.consumerGroup(consumerGroupName)
.credential(eventHubNamespace, eventHubName, credential)
.checkpointStore(new SampleCheckpointStore())
.processEvent(eventContext -> {
System.out.println(
"Partition ID = " +
eventContext.getPartitionContext().getPartitionId() +
" and sequence number of event = " +
eventContext.getEventData().getSequenceNumber());
})
.processError(errorContext -> {
System.out.println(
"Error occurred while processing events " +
errorContext.getThrowable().getMessage());
})
.buildEventProcessorClient();
To use DefaultAzureCredential in a Node.js application, install the @azure/identity package:
npm install --save @azure/identity
At the top of your file, add the following code:
import { DefaultAzureCredential } from "@azure/identity";
Identify the locations in your code that create an EventHubProducerClient or EventHubConsumerClient object to connect to Azure Event Hubs. Update your code to match the following example:
To use DefaultAzureCredential in a Python application, install the azure-identity package:
pip install azure-identity
At the top of your file, add the following code:
from azure.identity import DefaultAzureCredential
Identify the locations in your code that create an EventHubProducerClient or EventHubConsumerClient object to connect to Azure Event Hubs. Update your code to match the following example:
Make sure to update the event hubs namespace in the URI of your EventHubProducerClient or EventProcessorClient objects. You can find the namespace name on the overview page of the Azure portal.
Run the app locally
After making these code changes, run your application locally. The new configuration should pick up your local credentials, such as the Azure CLI, Visual Studio, or IntelliJ. The roles you assigned to your user in Azure allows your app to connect to the Azure service locally.
Configure the Azure hosting environment
Once your application is configured to use passwordless connections and runs locally, the same code can authenticate to Azure services after it's deployed to Azure. The sections that follow explain how to configure a deployed application to connect to Azure Event Hubs using a managed identity. Managed identities provide an automatically managed identity in Microsoft Entra ID for applications to use when connecting to resources that support Microsoft Entra authentication. Learn more about managed identities:
You can create a user-assigned managed identity using the Azure portal or the Azure CLI. Your application uses the identity to authenticate to other services.
At the top of the Azure portal, search for Managed identities. Select the Managed Identities result.
Select + Create at the top of the Managed Identities overview page.
On the Basics tab, enter the following values:
Subscription: Select your desired subscription.
Resource Group: Select your desired resource group.
Region: Select a region near your location.
Name: Enter a recognizable name for your identity, such as MigrationIdentity.
Select Review + create at the bottom of the page.
When the validation checks finish, select Create. Azure creates a new user-assigned identity.
After the resource is created, select Go to resource to view the details of the managed identity.
Use the az identity create command to create a user-assigned managed identity:
az identity create --name MigrationIdentity --resource-group <your-resource-group>
Associate the managed identity with your web app
You need to configure your web app to use the managed identity you created. Assign the identity to your app using either the Azure portal or the Azure CLI.
You can assign a managed identity to a virtual machine with the az vm identity assign command.
az vm identity assign \
--resource-group <resource-group-name> \
--name <virtual-machine-name>
--identities <managed-identity-id>
You can assign a managed identity to an Azure Kubernetes Service (AKS) instance with the az aks update command.
az aks update \
--resource-group <resource-group-name> \
--name <cluster-name> \
--enable-managed-identity \
--assign-identity <managed-identity-id> \
--assign-kubelet-identity <managed-identity-id>
You can use Service Connector to create a connection between an Azure compute hosting environment and a target service using the Azure CLI. The Service Connector CLI commands automatically assign the proper role to your identity. You can learn more about Service Connector and which scenarios are supported on the overview page.
Retrieve the client ID of the managed identity you created using the az identity show command. Copy the value for later use.
az identity show \
--name MigrationIdentity \
--resource-group <your-resource-group> \
--query clientId
Use the appropriate CLI command to establish the service connection:
Next, you need to grant permissions to the managed identity you created to access your event hub. Grant permissions by assigning a role to the managed identity, just like you did with your local development user.
Navigate to your event hub overview page and select Access Control (IAM) from the left navigation.
Choose Add role assignment
In the Role search box, search for Azure Event Hubs Data Sender, which is a common role used to manage data operations for queues. You can assign whatever role is appropriate for your use case. Select the Azure Event Hubs Data Sender from the list and choose Next.
On the Add role assignment screen, for the Assign access to option, select Managed identity. Then choose +Select members.
In the flyout, search for the managed identity you created by name and select it from the results. Choose Select to close the flyout menu.
Select Next a couple times until you're able to select Review + assign to finish the role assignment.
Repeat these steps for the Azure Event Hub Data Receiver role.
To assign a role at the resource level using the Azure CLI, you first must retrieve the resource ID using the az eventhubs eventhub show show command. You can filter the output properties using the --query parameter.
az eventhubs eventhub show \
--resource-group '<your-resource-group-name>' \
--namespace-name '<your-event-hubs-namespace>' \
--name '<your-event-hub-name>' \
--query id
Copy the output ID from the preceding command. You can then assign roles using the az role assignment command of the Azure CLI.
az role assignment create --assignee "<user@domain>" \
--role "Azure Event Hubs Data Receiver" \
--scope "<your-resource-id>"
az role assignment create --assignee "<user@domain>" \
--role "Azure Event Hubs Data Sender" \
--scope "<your-resource-id>"
If you connected your services using Service Connector you don't need to complete this step. The necessary role configurations were handled for you when you ran the Service Connector CLI commands.
Update the application code
You need to configure your application code to look for the specific managed identity you created when it's deployed to Azure. In some scenarios, explicitly setting the managed identity for the app also prevents other environment identities from accidentally being detected and used automatically.
On the managed identity overview page, copy the client ID value to your clipboard.
DefaultAzureCredential credential = new DefaultAzureCredentialBuilder()
.managedIdentityClientId(managedIdentityClientId)
.build();
Create a DefaultAzureCredentialClientIdOptions object with its managedIdentityClientId property set to the client ID. Pass that object to the DefaultAzureCredential constructor.
const credential = new DefaultAzureCredential({
managedIdentityClientId
});
Redeploy your code to Azure after making this change in order for the configuration updates to be applied.
Test the app
After deploying the updated code, browse to your hosted application in the browser. Your app should be able to connect to the event hub successfully. Keep in mind that it can take several minutes for the role assignments to propagate through your Azure environment. Your application is now configured to run both locally and in a production environment without the developers having to manage secrets in the application itself.
Next steps
In this tutorial, you learned how to migrate an application to passwordless connections.
You can read the following resources to explore the concepts discussed in this article in more depth: