Most Service Bus examples use symmetric keys directly in applications needing access to the ServiceBus, usually as part of the connection string. That approach does not work so well with widely distributed applications, e.g. desktop or mobile apps. Another important Azure service becomes very useful here: Azure Active Directory. One of the goals of AAD is to provide role and group based authorization for users to access resources. It allows us have a flexible and easy to manage way of defining which users, coming to AAD through a desktop or mobile application are allowed what kind of access to specific resources. In this case, the Service Bus is such a resource.
This example shows how to use Azure AD and a custom server-side application to authenticate clients and authorize them to obtain access to selected Service Bus functionality, e.g. Send. It relies on the fact that the connection string, symmetric key based approach in fact creates a Shared Access Signature, which in turn is used to access the ServiceBus. In this example the connection string, stored in a well protected server application is used to generated the SAS string and hand it over to the client application, based on how the client was authorized to access the ServiceBus in the Azure AD. The basic flow is as on the diagram below:
Code for the sample is attached to this blog. The solution consists of two projects: a WPF client application and a WebAPI server application. To enable the OAuth2 flow, both are set up in an Azure AD tenant as per the Native-WebApi sample: http://github.com/AzureADSamples/NativeClient-DotNet. Furthermore, the WebApi application defines two Roles in Azure AD as per: http://blogs.technet.com/b/ad/archive/2014/12/18/azure-active-directory-now-with-group-claims-and-application-roles.aspx. Based on the Role assigned to user signing in through the Client Application, the WebApi server application issues a SAS string granting the client rights to perform the appropriate operations against the Service Bus. For this sample the Service Bus was set up with two permission sets, one for Sender role and one for Receiver role, using the Azure Portal UI: