简体   繁体   中英

HTTPClient and JWT Authentication in C#

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);
}

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

您已经通过简单地删除输入上的“Bearer”来解决问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM