I am trying to access `Azure Service Bus` `Queue` from my `Windows Service` application.
I am following [this](https://github.com/Azure/azure-service-bus/blob/master/samples/DotNet/Microsoft.ServiceBus.Messaging/RoleBasedAccessControl/Program.cs) sample.
I want to protect this `Azure Service Bus` using `Azure Service Principal` Below are the steps I have implemented
1. Register an application named `pc-shutdown-producer` in `Azure Ad`
representing my `Windows Service`
2. I have created my Azure `service bus namespace` named `shutdowncomputer`
3. Inside `Access control (IAM)`, I have added `Role Assignment` with below values
- Role - `Azure Service Bus Data Owner`
- Assign access to - `pc-shutdown-producer`
As per my knowledge above configuration will let `pc-shutdown-producer` application to manage all the resources in the servicebus namespace.
4. Apart from this, I have also provided `pc-shutdown-producer` delegated API Permissions to access the service bus namespace.
Below is my C# code.
public async Task Init()
{
string authority = $"https://login.windows.net/{TenantId}";
ITokenProvider tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(AuthenticationCallback, authority);
var endpoint = new Uri($"sb://shutdowncomputer.servicebus.windows.net/");
var entityPath = "shutdownrequest";
var qc = new QueueClient(endpoint.ToString(), entityPath, tokenProvider);
Message m = new Message();
m.Body = Encoding.ASCII.GetBytes("{id: 1, name: 'hemant'}");
m.ContentType = "application/json";
try
{
await qc.SendAsync(m);
}
catch (Exception ex)
{
//I am getting exception here.
//Unauthorized access. 'Send' claim(s) are required to perform this operation.
throw ex;
}
}
private async Task<string> AuthenticationCallback(string audience, string authority, object state)
{
string accessToken = string.Empty;
IConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(AppId)
.WithAuthority(authority)
.WithClientSecret(Password)
.Build();
var serviceBusAudience = new Uri("https://servicebus.azure.net");
List<string> claims = new List<string>();
claims.Add($"{serviceBusAudience}/.default");
try
{
var result = await app.AcquireTokenForClient(claims.ToArray()).ExecuteAsync();
accessToken = result.AccessToken;
}
catch (Exception ex)
{
//No issue here.
Console.WriteLine(ex.Message);
}
//Successfully able to retrieve a token.
return accessToken ;
}
Upon executing `Init()` , I am getting below exception message.
`Unauthorized access. 'Send' claim(s) are required to perform this operation. Resource: 'sb://shutdowncomputer.servicebus.windows.net/shutdownrequest'. TrackingId:52c0eedcf19d4513a8ec105943859764_G12, SystemTracker:gateway7, Timestamp:2020-05-11T06:59:01`
Thanks
Regards, Hemant Shelar