Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTPClient and JWT Authentication in C#

Tags:

c#

jwt

I'm having a hard time trying to use authorization in C# Winforms. My purpose is to access the API. I already get the access token but when I try to pass it to the header, it returns an error:

HTTP error 400.

My code:

using (var httpClient = new HttpClient())
{
    var url = @"https://acerportal.com/v1/414232363/status/device/";
    httpClient.BaseAddress = new Uri(url);
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", accessToken);

    var response = await httpClient.GetStringAsync(url);
    string checkResult = response.ToString();
    MessageBox.Show(checkResult);
}
like image 604
Ran Avatar asked Nov 13 '18 04:11

Ran


1 Answers

The header has to look a little different, the format is Authorization: <type> <credentials> - so it's like this for jwt:

httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);

For an explanation, also see https://security.stackexchange.com/questions/108662/why-is-bearer-required-before-the-token-in-authorization-header-in-a-http-re

like image 123
BrokenGlass Avatar answered Nov 14 '22 22:11

BrokenGlass