【问题标题】:How to add www-authenticate header to HttpListenerResponse in .NET如何在 .NET 中将 www-authenticate 标头添加到 HttpListenerResponse
【发布时间】:2018-03-21 15:45:03
【问题描述】:

我有一个带有自定义自托管服务器(没有 IIS,没有 WCF)的自定义 Web 堆栈。它使用 HttpListener 来获取由模块管道处理的 HttpListenerContext。所以,我正在处理模块中使用 HttpListenerRequestHttpListenerRespose

现在我需要在某些特定情况下向客户端返回401 Unauthorized。响应还应包括带有特定挑战的 WWW-Authenticate 标头。所以,我可以设置 HttpListenerRespose = 401 的 StatusCode 并且它工作正常。但是当我尝试将 Www-Authenticate 标头添加到响应中时 - 我得到一个异常:“必须使用适当的属性或方法修改 'WWW-Authenticate' 标头。参数名称:名称”。

正如我所见,WWW-Authenticate 标头受到响应保护。 MSDN Documentation 说我不能“使用 Headers 属性设置 Content-Length、Keep-Alive、Transfer-Encoding 或 WWW-Authenticate 标头”。其中两个有 KeepAlive 和 ContentLenght64 属性,但是“您不能手动设置 Transfer-Encoding 或 WWW-Authenticate 标头”

那么,什么是可能的解决方案?我应该如何正确返回带有特定 WWW-Authenticate 标头的 401 响应?

【问题讨论】:

  • 在监听器上设置——HttpListener.AuthenticationSchemes(你想要Basic)
  • 谢谢你,亚历克斯。这似乎是我需要的。那么,如果我想在标题中指定类似 'Token realm='myrealm', error='token_expired'' 怎么办?
  • 根据stackoverflow.com/questions/33290559/… 主题,System.Net.HttpListener 似乎只支持内置的身份验证模式。并且无法将其配置为与 JWT 一起使用(在我的情况下)。伤心。

标签: c# .net header system.net www-authenticate


【解决方案1】:

HttpListenerResponse.AddHeader 绕过了这个限制。见https://referencesource.microsoft.com/#System/net/System/Net/HttpListenerResponse.cs,265

【讨论】:

    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 2014-04-10
    • 1970-01-01
    • 2016-06-02
    • 2018-10-19
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    相关资源
    最近更新 更多