如何使用Dot-NET HttpClient获取完整的WWW-Authenticate标头?

时间:2014-10-10 13:26:29

标签: c# azure oauth dotnet-httpclient www-authenticate

方案

我正在开发一个适用于Windows Phone 8的网络程序(我觉得这不重要)并使用Microsoft HTTP Client Libraries

问题

当用户尝试获取URL时,我需要知道当响应为401时需要什么类型的身份验证。 如果是NTLM,Basic,Digest等,这很容易;所有受支持的WinHTTP方案。 您可以使用以下代码获取URL:

HttpResponseMessage response;
using (var httpClient = new HttpClient(httpHandler))
{
     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, authenticationUri);
     response = await httpClient.SendAsync(request, _cancelTokenSource.Token);
}

检查所需身份验证的最简单方法是使用Headers.WwwAuthenticate.Contains方法,例如检查是否需要NTLM方案:

string scheme = "NTLM";
bool requiredScheme = response.Headers.WwwAuthenticate.Contains(new System.Net.Http.Headers.AuthenticationHeaderValue(scheme));

如果scheme = "Bearer"那么它总是给出错误。

获取响应标头

尝试访问需要Azure Active Directory身份验证的服务器时,获得了以下内容。

Jason Chrome App

使用Jason Chrome App从Web服务器获取响应标头,我收到了:

Pragma: no-cache
Date: Fri, 10 Oct 2014 11:39:02 GMT
WWW-Authenticate: Bearer authorization_uri="https://login.windows.net/common",
    error="invalid_token", 
    error_description="The access token is missing", 
    NTLM
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Expires: -1
Cache-Control: no-cache
Content-Length: 0
X-UA-Compatible: IE=EmulateIE7

Dot-Net Http Client

使用HttpClient System.Net.Http.HttpResponseMessageresponse)给出:

StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 0.0, Content: System.Net.Http.StreamContent, Headers:
    {
      Server: Microsoft-IIS/7.5
      WWW-Authenticate: NTLM
      X-Powered-By: ASP.NET
      X-UA-Compatible: IE=EmulateIE7
      Date: Fri, 10 Oct 2014 11:25:04 GMT
      Content-Length: 1293
      Content-Type: text/html
    }

WWW-认证比较

从以上结果可以进行以下比较。

Jason Chrome App

  

Bearer authorization_uri =“https://login.windows.net/common”,   错误= “INVALID_TOKEN”,   error_description =“缺少访问令牌”,

     

NTLM

Dot-Net Http Client

  

NTLM

承载部分被Http客户端丢弃(或者这可能是HttpResponseMessage的限制),只剩下NTLM身份验证。

问题

如何或在何处使用显示所有方案及其内容的Dot-NET HttpClient获取完整的WWW-Authenticate标头?这个例子特定于Bearer;但是,其他(自定义)方案也存在。

有什么想法吗?


其他

即使在Windows.Web.Http.HttpClient

上,同样的问题似乎仍然存在

0 个答案:

没有答案