Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient Authorization Header Invalid Format

When I try to make a GET request with the address and Authorization value below, I have no problems.

Address: http://example.com/xyz.svc/branches/?latitude=0&longitude=0&range=20000

Header Key: Authorization

Value: example;foo

When I try it with HttpCLient I get format invalid error for the authorization header value

This is how I tried

HttpClient client = new HttpClient();

    string latitude = "0";
    string longitude = "0";
    string range = "2000";

    string uri = "/xyz.svc/branches/?latitude=0&longitude=0&range=20000;

    string value = "foo";

    client.BaseAddress = new Uri("http://example.com");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    client.DefaultRequestHeaders.Add("Authorization", String.Format("example;{0}", value));

    HttpResponseMessage response = await client.GetAsync(uri);

    var responseJson = await response.Content.ReadAsStringAsync();

    Console.WriteLine(responseJson);

What am I doing wrong?

like image 514
Ege Bayrak Avatar asked Apr 13 '18 14:04

Ege Bayrak


People also ask

How do I send authorization header in URL?

It is indeed not possible to pass the username and password via query parameters in standard HTTP auth. Instead, you use a special URL format, like this: http://username:[email protected]/ -- this sends the credentials in the standard HTTP "Authorization" header.

How do I add authorization header in GET request?

To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.


1 Answers

Normally that authorization header has a format as {scheme} {token} which is what it is trying to validate with your current code.

Some servers can be configured to accept different formats. To avoid the client validating the standard format use TryAddWithoutValidation

client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", String.Format("example;{0}", value));

which based on your example would have the following request headers

Accept application/json
Authorization example;foo
like image 132
Nkosi Avatar answered Sep 21 '22 16:09

Nkosi