Adding authorization to the headers

Jimmyt1988 picture Jimmyt1988 · Sep 26, 2013 · Viewed 79k times · Source

I have the following code:

...
AuthenticationHeaderValue authHeaders = new AuthenticationHeaderValue("OAuth2", Contract.AccessToken);
string result = await PostRequest.AuthenticatedGetData(fullUrl, null, authHeaders);
return result; 
...

public static async Task<string> AuthenticatedGetData(string url, FormUrlEncodedContent data, AuthenticationHeaderValue authValue)
{

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(authValue.Parameter);

    HttpResponseMessage response = await client.PostAsync(new Uri(url), data);

    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();
    return responseBody;
}

The response = await part just continues an ongoing loop and nothing happens. Any ideas what I am doing wrong?

The question really is, how do I send the following header:

Authorization: OAuth2 ACCESS_TOKEN

to an external web api

Answer

John picture John · Jul 4, 2014

I struggled with this. I kept getting an error saying "invalid format" because I have a custom implementation and the Authorization header is validated against certain standards. Adding the header this way however worked:

var http = new HttpClient();
http.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "key=XXX");