我正在使用 httpClient 调用受 Azure AAD 保护的 WebApi。 我调用 MSAL 库来获取令牌并设置标头,如下所示。
private async void SetHeaders(HttpClient HttpClientObj)
{
IConfidentialClientApplication app;
app = ConfidentialClientApplicationBuilder.Create(_configurationSettings.TestAppClientId)
.WithClientSecret(_configurationSettings.TestAppClientSecret)
.WithAuthority(new Uri(_configurationSettings.TestAppInstance + _configurationSettings.TestAppTenantId))
.Build();
AuthenticationResult result = null;
IEnumerable<string> scopes = new List<string>() { _configurationSettings.TestAppAuthScope };
try
{
result = await app.AcquireTokenForClient(scopes)
.ExecuteAsync();
}
catch (MsalServiceException ex)
{
_logger.LogError("Exception Message: {ex}");
}
var defaultRequestHeaders = HttpClientObj.DefaultRequestHeaders;
defaultRequestHeaders.Clear();
if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
{
HttpClientObj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
try
{
defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
}
catch (Exception ex)
{
_logger.LogError("Exception Message: {ex}");
}
}
private async Task<HttpResponseMessage> CallTestAppAPIToGetDataAsync(string testAppUri)
{
HttpResponseMessage response = null;
HttpClient testHttpClientObj = new HttpClient();
SetHeaders(testHttpClientObj);
response = await testHttpClientObj.GetAsync(requestUri: gridstateUri);
return response;
}
我在 httpClientObj 调用 API 的行中添加了一个断点,我可以看到具有正确值的授权令牌。 当我尝试在邮递员中使用相同的标记访问相同的 uri 时,它工作正常,但在这里它给出了 401 Unauthorized。
response = await testHttpClientObj.GetAsync(requestUri: gridstateUri);
您已将
SetHeaders
方法声明为 async
并使用 await inside
,因此请尝试通过将声明更改为 async Task
来修复您的代码
private async Task SetHeaders(HttpClient HttpClientObj)
{
...
}
然后通过
await SetHeaders(testHttpClientObj)
等待此方法的结果,否则程序将继续而不等待任务完成