为什么 AuthenticationHeaderValue 需要 scheme?

Why is the scheme required for AuthenticationHeaderValue?

我正在按以下方式设置 HttpClient 的授权 header:

httpClient
    .DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(null, "abc");

...但出现异常:

"scheme" of the AuthenticationHeaderValue cannot be null.

为什么AuthenticationHeaderValue一定要有方案?这是特定 RFC 所要求的吗?

方案用于确定您使用的身份验证类型:

  • 基本
  • Oauth
  • 承载者
  • 摘要
  • 等等

header 将如下所示:

{
   "key": "Authorization",
   "value": "<scheme> <parameter>"
}

尝试使用 Postman 查看根据 HTTP 支持的不同类型的身份验证生成的内容。

有时您无法使用方案设置授权 header。我现在正在做的一个项目也是如此。我需要从 TOPdesk 连接到 API,但没有指定方案。

来自 TOPdesk 的授权 header 必须具有类似于 TOKEN id="0d1739df-8952-41c0-94cd-b25287446b22" 的值,因此我无法使用方案。我通过添加授权 header 解决了这个问题,就像下面的例子一样,它就像一个魅力。

client.DefaultRequestHeaders.Add("Authorization", $"TOKEN id=\"{token}\"");

我知道这是一个老问题,但我想也许将来有人会看到这个答案并发现它有用。我也遇到过这个问题。