Search code examples
c#dotnet-httpclientnswag

How to add bearer token to autogenerated OpenApiToCSharpClient?


I have client generated using OpenApiToCSharpClient but each request is 401 unauthorized. I have added bearer token in HttpClient like this:

ClientEngine.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.Token);

and generated client is used like this:

 var userClient = new UserClient(HttpClient);
 UserAll.AddRange(await userClient.GetAllAsync());

but problem is that auth header isn't added to request (autogenerated code follows):

...
request_.Method = new System.Net.Http.HttpMethod("GET");
                request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json"));

PrepareRequest(client_, request_, urlBuilder_);
var url_ = urlBuilder_.ToString();
request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute);
PrepareRequest(client_, request_, url_);

var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false);
var disposeResponse_ = true;
...

Request is sent but only the client_ object has authorization headers but request_ does not. As far as I know, authorization headers should be also added to request but they aren't. I don't have any property related to authorization in nswag.json file - only following properties are related to HttpClient:

  "disposeHttpClient": true,
  "injectHttpClient": true,
  "httpClientType": "System.Net.Http.HttpClient",

What is missing?


Solution

  • Everything above is correct but apparently, automatic redirection to https was issue - somehow, when request is upgraded from http to https (automatically), it strips the headers. Interestingly enough, Postman didn't have this problem, only HttpClient.

    Solution - in Startup.cs, do this:

     if (!env.IsDevelopment())
     {
         app.UseHttpsRedirection();
     }