0

I am trying to POST a JSON with HhttpClient using a permanent token authorization, but I always get an error 401 Unauthorized code:

public static async Task<Uri> CrearitemAsync(Item item)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(BaseUri);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("OAuth", AuthToken);
        HttpResponseMessage response = await client.PostAsJsonAsync(
            "items/" + IdProvider, JsonConvert.SerializeObject(item));
        response.EnsureSuccessStatusCode();
        return response.Headers.Location;
    }
}

I also tried this:

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + AuthToken);

The token seems to be fine. It is an alphanumeric string all lower case. Is this the correct way to use a permanent token?

update The key i have to use for the header is: IDENTITY_KEY but still failing

Rarm
  • 101
  • 1
  • 2
  • 9
  • 1
    Not directly related, but [you are using `HttpClient` wrong](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/). – Bradley Uffner Sep 26 '17 at 18:15
  • Possible duplicate of [Setting Authorization Header of HttpClient](https://stackoverflow.com/questions/14627399/setting-authorization-header-of-httpclient) – Cory Sep 26 '17 at 18:16
  • Don't serialize item manually (JsonConvert.SerializeObject). Just pass *item* to PostAsJsonAsync. (or use *StringContent* and *JsonConvert.SerializeObject*) to do it manually – L.B Sep 26 '17 at 18:17
  • Seems to be a duplicate as Cory pointed out but still I am not sure if this is the correct way to use a permanent token, thanks for the comments – Rarm Sep 27 '17 at 06:50
  • the header key i have to use is: IDENTITY_KEY but still error 401 – Rarm Sep 27 '17 at 09:22

1 Answers1

1

finally it worked with Add.. had to use this 'key' value rather than authorization in the header:

client.DefaultRequestHeaders.Add("IDENTITY_KEY", AuthToken);
Rarm
  • 101
  • 1
  • 2
  • 9