我正在尝试Azure Service Bus
Queue
从我的Windows Service
应用程序访问。我正在关注这个示例。
我想保护它Azure Service Bus
使用Azure Service Principal
以下是我已实施的步骤
- 注册一个
代表我
pc-shutdown-producer
的应用程序Azure Ad
Windows Service
- 我创建了
service bus namespace
名为shutdowncomputer
- 在里面
Access control (IAM)
,我添加Role Assignment
了以下值- 角色 -
Azure Service Bus Data Owner
- 分配访问权限 -
pc-shutdown-producer
- 角色 -
据我所知,上述配置将让pc-shutdown-producer
应用程序管理 servicebus 命名空间中的所有资源。4. 除此之外,我还提供pc-shutdown-producer
了访问服务总线命名空间的委托 API 权限。
下面是我的 C# 代码。
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 ;
}
执行后Init()
,我收到以下异常消息。
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
更新 1
根据@Carl Zhao 的建议,我已经提供了管理员同意,pc-shutdown-producer
但仍然遇到同样的问题。
谢谢