未经授权 401 错误在使用 C# 中的 httpClient 时发生。

huangapple go评论108阅读模式
英文:

unauthorized 401 error while using httpClient in C#

问题

Here is the translated code:

  1. 我正在使用httpClient调用受Azure AAD保护的WebApi
  2. 我调用MSAL库来获取令牌并设置如下标头
  3. private async void SetHeaders(HttpClient HttpClientObj)
  4. {
  5. IConfidentialClientApplication app;
  6. app = ConfidentialClientApplicationBuilder.Create(_configurationSettings.TestAppClientId)
  7. .WithClientSecret(_configurationSettings.TestAppClientSecret)
  8. .WithAuthority(new Uri(_configurationSettings.TestAppInstance + _configurationSettings.TestAppTenantId))
  9. .Build();
  10. AuthenticationResult result = null;
  11. IEnumerable<string> scopes = new List<string>() { _configurationSettings.TestAppAuthScope };
  12. try
  13. {
  14. result = await app.AcquireTokenForClient(scopes)
  15. .ExecuteAsync();
  16. }
  17. catch (MsalServiceException ex)
  18. {
  19. _logger.LogError("Exception Message: {ex}");
  20. }
  21. var defaultRequestHeaders = HttpClientObj.DefaultRequestHeaders;
  22. defaultRequestHeaders.Clear();
  23. if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json"))
  24. {
  25. HttpClientObj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
  26. }
  27. try
  28. {
  29. defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
  30. }
  31. catch (Exception ex)
  32. {
  33. _logger.LogError("Exception Message: {ex}");
  34. }
  35. }
  36. private async Task<HttpResponseMessage> CallTestAppAPIToGetDataAsync(string testAppUri)
  37. {
  38. HttpResponseMessage response = null;
  39. HttpClient testHttpClientObj = new HttpClient();
  40. SetHeaders(testHttpClientObj);
  41. response = await testHttpClientObj.GetAsync(requestUri: gridstateUri);
  42. return response;
  43. }

Please note that code translation might be context-dependent, and it's important to ensure that the variables and configuration settings match your specific implementation.

英文:

I am using httpClient to call a WebApi protected with Azure AAD.
I call the MSAL library to fetch the token and set up the headers like below.

  1. private async void SetHeaders(HttpClient HttpClientObj)
  2. {
  3. IConfidentialClientApplication app;
  4. app = ConfidentialClientApplicationBuilder.Create(_configurationSettings.TestAppClientId)
  5. .WithClientSecret(_configurationSettings.TestAppClientSecret)
  6. .WithAuthority(new Uri(_configurationSettings.TestAppInstance + _configurationSettings.TestAppTenantId))
  7. .Build();
  8. AuthenticationResult result = null;
  9. IEnumerable&lt;string&gt; scopes = new List&lt;string&gt;() { _configurationSettings.TestAppAuthScope };
  10. try
  11. {
  12. result = await app.AcquireTokenForClient(scopes)
  13. .ExecuteAsync();
  14. }
  15. catch (MsalServiceException ex)
  16. {
  17. _logger.LogError(&quot;Exception Message: {ex}&quot;);
  18. }
  19. var defaultRequestHeaders = HttpClientObj.DefaultRequestHeaders;
  20. defaultRequestHeaders.Clear();
  21. if (defaultRequestHeaders.Accept == null || !defaultRequestHeaders.Accept.Any(m =&gt; m.MediaType == &quot;application/json&quot;))
  22. {
  23. HttpClientObj.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(&quot;application/json&quot;));
  24. }
  25. try
  26. {
  27. defaultRequestHeaders.Authorization = new AuthenticationHeaderValue(&quot;Bearer&quot;, result.AccessToken);
  28. }
  29. catch (Exception ex)
  30. {
  31. _logger.LogError(&quot;Exception Message: {ex}&quot;);
  32. }
  33. }
  1. private async Task&lt;HttpResponseMessage&gt; CallTestAppAPIToGetDataAsync(string testAppUri)
  2. {
  3. HttpResponseMessage response = null;
  4. HttpClient testHttpClientObj = new HttpClient();
  5. SetHeaders(testHttpClientObj);
  6. response = await testHttpClientObj.GetAsync(requestUri: gridstateUri);
  7. return response;
  8. }

I added one breakpoint in line where the httpClientObj calls the API and I can see the Authorization token with the correct value.
When I try to hit the same uri with in postman with the same token it works fine, but here it gives 401 Unauthorized.

  1. response = await testHttpClientObj.GetAsync(requestUri: gridstateUri);

未经授权 401 错误在使用 C# 中的 httpClient 时发生。

答案1

得分: 3

你已经将SetHeaders方法声明为async,并在内部使用await,所以尝试通过将声明更改为async Task来修复你的代码。

  1. private async Task SetHeaders(HttpClient HttpClientObj)
  2. {
  3. ...
  4. }

然后通过await SetHeaders(testHttpClientObj)等待此方法的结果,否则程序将在等待任务完成之前继续执行。

英文:

You have declared SetHeaders method as async and using await inside, so try fixing your code by changing declaration to async Task

  1. private async Task SetHeaders(HttpClient HttpClientObj)
  2. {
  3. ...
  4. }

and then awaiting the result of this method by await SetHeaders(testHttpClientObj) otherwise the program continues without waiting for the task to complete

huangapple
  • 本文由 发表于 2023年5月17日 15:59:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269774.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定