【问题标题】:HTTPClient and JWT Authentication in C#C# 中的 HTTPClient 和 JWT 身份验证
【发布时间】:2019-04-15 20:50:36
【问题描述】:

我很难在 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);
}

【问题讨论】:

  • 如果“Basic”不起作用,请尝试“Bearer”,因为在撰写本文时,“Bearer”是 aspnetcore 中 JWT 的默认方案。

标签: c# jwt


【解决方案1】:

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

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

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

【讨论】:

  • 我在使用它时仍然收到错误的请求。
  • 那么问题可能出在其他地方 - 您确定令牌确实有效吗?
【解决方案2】:

您好,只需删除输入中的“Bearer”即可解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 2020-07-23
    • 2019-02-14
    • 1970-01-01
    • 1970-01-01
    • 2023-01-22
    • 2018-12-06
    相关资源
    最近更新 更多