1

I'm calling a simple REST API that I deployed on Azure app service that returns "checked" string, while the request needs a bearer token that I generate using OAuth 2.0, the request on Postman passes with no issues. But when I take the same code that postman generates on my .net 4.8 c# it fails on Http error Unauthorized (401)

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LoginService.GetAAdAccessToken()); // The token is valid at this point and I test it on Postman

Task<HttpResponseMessage> result = null;
var postCall = new Task(() => result = client.GetAsync("https://myapp.dev.com/api/check"));
postCall.RunSynchronously();
Task<string> httpResponse = null;
var postCallRes = new Task(() => httpResponse = result.Result.Content.ReadAsStringAsync());
postCallRes.RunSynchronously();   // Returns 401
Console.WriteLine(httpResponse.Result)

Any idea why the .net fails?

I tried to use different web services and to try them, SOAP & REST, both from .net 4.8 returns 401.

  • The issue with your code is that you are passing the result of the GetAAdAccessTokenAsync() method directly to the AuthenticationHeaderValue constructor, instead of awaiting its completion and passing the actual token string. This means that the Authorization header is being set with a Task object instead of a string token. – rahularyansharma May 02 '23 at 14:01
  • The name is miss leading, sorry for not removing that, the method returns non async token which populated on the request on runtime. – HasaN MasarwaH May 02 '23 at 14:38

1 Answers1

0

I used the below code in the 4.8 Framework and able to call the API from the code and postman.

  var Mytoken = "MyToken";
  var url = "My API";

  using (var clnt = new HttpClient())
       {
          clnt.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Mytoken);
          var req = new HttpRequestMessage(HttpMethod.Get, url);
          var resp = await clnt.SendAsync(req);
          if (resp.IsSuccessStatusCode)
             {
                 var result = await resp.Content.ReadAsStringAsync();
                 Console.WriteLine(result);
              }
            else
              {
                  Console.WriteLine($"Failed to call API.... {resp.StatusCode}");
              }
        }

enter image description here

enter image description here

For further check the below steps.

  • Check the bearer token in the Authorization header of the HTTP request. You can check this from the HTTP request generated by Postman and compare it to the HTTP request generated by the code.

  • You need to pass bearer token as a string, else it has to be serialized.

  • If the bearer token is being cached by the HttpClient, it will not be updated with the new token. For this check the HttpClient instance is not being reused in any other requests.

  • Verify that the OAuth 2.0 provider is returning a token that is valid for the Azure App Service.

For more information refer to the SO Link.

Rajesh Mopati
  • 1,329
  • 1
  • 2
  • 7