Jacob
Jacob

Reputation: 587

Using HttpClient, send an Authorization token with no schema

Note: This question is similar to this one, but its suggested answer doesn't apply here.

I am trying to access this API, which is looking for a header that looks like this:

Authorization: {token}

Note the absence of any authentication scheme.

I have tried doing:

myHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("", authToken);

Which resulted in an ArgumentException saying that I can't pass an empty string.

I have also tried both:

myHttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(authToken);

and

myHttpClient.DefaultRequestHeaders.Add("Authorization", authToken);

Both of which result in a FormatException.

There seems to be something forcing me to conform to a standard format for my authorization header, but the service I am trying to access doesn't use that standard format.

Upvotes: 11

Views: 7008

Answers (2)

Esra
Esra

Reputation: 1190

You could try:

request.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token));

as mentioned in https://learn.microsoft.com/en-us/dotnet/api/system.net.http.headers.httpheaders.tryaddwithoutvalidation.

Upvotes: 22

Jacob
Jacob

Reputation: 587

As seems to happen so often, right after I ask the question I find the answer.

The standard format that HttpClinet is holding me to is the Http protocol itself, which requires an authentication scheme, however there is a work-around.

instead of:

myHttpClient.DefaultRequestHeaders.Add("Authorization", authToken);

You can use:

myHttpClient.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", authToken);

Which ignores the Http standard and just lets you add the header however you need.

Upvotes: 9

Related Questions