0

I am trying to use C# HttpClient from ASP.NET MVC to make a request to an API. My API is running on .NET 6.0.

httpClient.BaseAddress = new Uri(_url);
httpClient.DefaultRequestHeaders.Clear();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer", $"{token}");
var serialized = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
var httpResponseMessage = await httpClient.PutAsync(urlToSend, serialized);

Here is my code. I tried all the possibilities I saw on google. But when sending request, I can't send Authorization header.

I can send it with Postman.

Here is my API code:

    [Consumes("application/json")]
    [Produces("application/json", "text/plain")]
    [ProducesResponseType(StatusCodes.Status200OK, Type = typeof(IResult))]
    [ProducesResponseType(StatusCodes.Status400BadRequest, Type = typeof(IResult))]
    [HttpPut("changeuserpassword")]
    public async Task<IActionResult> ChangeUserPassword([FromBody] ChangePasswordCommand changePasswordCommand)
    {
        var accessToken = Request.Headers[HeaderNames.Authorization];
        return GetResponseOnlyResult(await Mediator.Send(changePasswordCommand));
    }

Note: In my _url, I use http, not https.

KOMODO
  • 72
  • 1
  • 8

4 Answers4

1

I'm not sure but maybe the [AllowAnonymous]attribute remove the Authorization header from request just because it does not make sense if no authorization is needed. Have you checked if the sent request contains the header using a tool like fiddler ?

Olivier Duhart
  • 362
  • 3
  • 14
  • I tried but it does not work too. – KOMODO Aug 05 '22 at 06:49
  • 1
    have you check the sent request with fiddler ? yiou first need to know whether the header disapears ? client or server side ? My guess is that t'is client side. – Olivier Duhart Aug 05 '22 at 06:53
  • I don't know fiddler. I will do it. The second thing, When i add an other header like "custom-key" it works. The server API can see this header. But when I add "Authorization" it does not work. If I change to "Authorization-x" it works too. – KOMODO Aug 05 '22 at 07:12
1

I solved the problem by changing my base url from HTTP to HTTPS.

I tried with Fiddler and I got the same problem when I request to HTTP.

So thanks to @olivier-duhart .

KOMODO
  • 72
  • 1
  • 8
1

To add to the accepted answer, the problem gets solved by changing from HTTP to HTTPS is due to the fact that, the Authorization header gets stripped during redirects. This behavior is for security concerns and is by design, as mentioned in the github discussion here.

The same behavior may not be seen when using Postman vs HttpClient for example, is due to the way that different clients, have differing mechanisms, by which the subsequent requests (following a response status 30X) to the redirect location are handled.

Also a great answer elsewhere on stackoverflow : Authorization header is lost on redirect

0

Please review this link. Allow Anonymous will ignore the authentication header

https://github.com/dotnet/aspnetcore/issues/30546

I tried with the code. It seems working fine for me. Here is my code of console app

try
            {

                ChangePasswordCommand passobj = new ChangePasswordCommand() { password = "new password"};

                string _url = "https://localhost:44395/api/Values/";

                var httpClient = new HttpClient();
                httpClient.BaseAddress = new Uri(_url);
                httpClient.DefaultRequestHeaders.Clear();
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue($"Bearer", $"MYTOKEN");
                var serialized = new StringContent(JsonConvert.SerializeObject(passobj), Encoding.UTF8, "application/json");
                var httpResponseMessage = await httpClient.PutAsync("changeuserpassword", serialized);
            }
            catch (Exception ex) { 
            
            }

And here is controler Api

[AllowAnonymous]

    [Consumes("application/json")]
    [Produces("application/json", "text/plain")]
    
    [HttpPut("changeuserpassword")]
    public async Task<IActionResult> ChangeUserPassword(ChangePasswordCommand changePasswordCommand)
    {
        var accessToken = Request.Headers[HeaderNames.Authorization];

        return Ok();
    }
Atif Rehmat
  • 43
  • 1
  • 8