使用System.Net.Http.HttpClient逐步进行NTLM身份验证

时间:2017-03-06 14:01:53

标签: c# windows-runtime uwp ntlm

我试图自己实现NTLM身份验证。 问题是,当我尝试发送类型1消息(NEGOTIATE_MESSAGE)时,应用程序抛出异常:

  

发送请求时发生错误。

  

抛出异常:mscorlib.ni.dll中的'System.Runtime.InteropServices.COMException'

     

WinRT信息:登录请求被拒绝

这是我的代码:

byte[] type1Message = new byte[40]
{
    // 'N',  'T',  'L',  'M',  'S',  'S',  'P',  '\0'
       0x4E, 0x54, 0x4C, 0x4D, 0x53, 0x53, 0x50, 0x00,
    // Type 1 message
       0x01, 0x00, 0x00, 0x00,
    // Flags
       0x97, 0x82, 0x08, 0xe2,
    // Supplied Domain
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    // Supplied Workstation
       0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    // OS Version Structure
       0x0A, 0x00, 0x39, 0x38, //0x00, 0x00, 0x00, 0x00,
    // Os version uknown
       0x00, 0x00, 0x00, 0x0f
};

var _client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost:60475/");
request.Headers.Add("Authorization", "NTLM " + Convert.ToBase64String(type1Message));
using (var response = await _client.SendAsync(request))
{
    if (response.IsSuccessStatusCode)
    {
        return;
    }
    else
    {

    }
}

在Fiddler中,我看到请求已发送,我会收到正确答案。

请求标题:

GET http://localhost:60475/ HTTP/1.1
Authorization: Negotiate TlRMTVNTUAABAAAAl4II4gAAAAAAAAAAAAAAAAAAAAAKADk4AAAADw==
Host: localhost:60475
Connection: Keep-Alive

响应标题:

HTTP/1.1 401 Unauthorized
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
WWW-Authenticate: Negotiate TlRMTVNTUAACAAAAHgAeADgAAAAVgorixp1F6S8OipIAAAAAAAAAAJgAmABWAAAACgA5OAAAAA9EAEUAUwBLAFQATwBQAC0ATQA1ADMAUgBNAE8ASAACAB4ARABFAFMASwBUAE8AUAAtAE0ANQAzAFIATQBPAEgAAQAeAEQARQBTAEsAVABPAFAALQBNADUAMwBSAE0ATwBIAAQAHgBEAEUAUwBLAFQATwBQAC0ATQA1ADMAUgBNAE8ASAADAB4ARABFAFMASwBUAE8AUAAtAE0ANQAzAFIATQBPAEgABwAIALEnZjh/ltIBAAAAAA==
Date: Mon, 06 Mar 2017 13:40:29 GMT
Content-Length: 341
Proxy-Support: Session-Based-Authentication

我忘记了什么吗?

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是握手,所以你需要接受NTLM挑战,使用它的随机数,然后创建你自己的随机数,然后获取密码哈希并进行数学运算。这个网站很棒,附录中的java很容易转换为c# http://davenport.sourceforge.net/ntlm.html