C# 中的 HTTPClient 和 JWT 身份验证

Ran*_*Ran 4 c# jwt

我很难尝试在 C# Winforms 中使用授权。我的目的是访问 API。我已经获得了访问令牌,但是当我尝试将它传递给标头时,它返回一个错误:

HTTP 错误 400。

我的代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

Bro*_*ass 9

标题必须看起来有点不同,格式是Authorization: <type> <credentials>- 所以 jwt是这样的:

httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
Run Code Online (Sandbox Code Playgroud)

有关解释,另请参阅https://security.stackexchange.com/questions/108662/why-is-bearer-required-before-the-token-in-authorization-header-in-a-http-re