0

I am developing a RESTFUL API using django-rest-framework. And for Authorization I choose to use Token Authorization (not JWT). Below is what I tried:

Using POSTMAN (Works)

headers: 
Authorization: Token 329367424fd30a876ccff05dbc5a18d86fe7158c

Using C# Client (no working)

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Token 329367424fd30a876ccff05dbc5a18d86fe7158c");
await client.GetAsync(<url>)

// Authentication credentials were not provided.

After I debug and override TokenAuthentication function, I realize that Authorization headers is being removed if requested from C# Client.

EDIT:

Actually I have tried using Javascript and it works also, I think the problem is C# HttpClient.

I tried

HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization3", $"token {token}");
client.DefaultRequestHeaders.Add("Authorization", $"token {token}");

and I debug Authorization function in python, and I found out only Authorization3 was send to the server and Authorization wasn't

enter image description here

Sieryuu
  • 1,510
  • 2
  • 16
  • 41

2 Answers2

3

The reason Authorization header was missing is because of redirection. I am sorry for not posting my Uri string because I never though that is the problem.

My Uri string is http://localhost:3000/module?query=123. After calling GetAsync the Uri string become http://localhost:3000/module/?query=123 (extra slash after module). So the library detect it is a redirection.

So my quick fix is just modified the url to http://localhost:3000/module/?query=123

For those who want know whether it was cause by redirection or not can checkout this Link

Sieryuu
  • 1,510
  • 2
  • 16
  • 41
  • You saved my day :) I queried a ASP.NET Core WebAPI that automatically redirected me to HTTPS when calling the respective HTTP endpoint, which caused my `Authorize`-Header to vanish. – Paul Kertscher Mar 31 '22 at 07:58
1

Use HttpClient like below :

            using (var client = new HttpClient())
            {
                var request = new HttpRequestMessage();
                request.RequestUri = new Uri("url");
                request.Method = HttpMethod.Get;
                //request.Content = new StringContent("body", Encoding.UTF8, "application/json");               
                request.Headers.TryAddWithoutValidation("Authorization", "Token 329367424fd30a876ccff05dbc5a18d86fe7158c");
                var getResponse = await client.SendAsync(request);
                using (HttpContent content = getResponse.Content)
                {
                    var result = await content.ReadAsStringAsync();
                }
            }