1

编写一个 dotnet 核心应用程序。我需要使用网络凭据登录,因为服务(恰好是 TFS 本地服务器)使用这些凭据进行身份验证。在我(和另一个团队成员)的 Windows 机器上,以下代码有效:

Console.WriteLine("Type in your DOMAIN password:");
var pass = GetPassword(); //command line secure string magic from SO
var networkCredential = new NetworkCredential("USERNAME", pass, "DOMAINNAME");
string tfsDefaultCollection = "https://TFSURL/DefaultCollection";

string testUrl = $"{tfsDefaultCollection}/_apis/tfvc/changesets/1234/changes?api-version=2.2";

var httpClientHandler = new HttpClientHandler
{
    Credentials = networkCredential
};

var client = new HttpClient(httpClientHandler)
{
    BaseAddress = new Uri(testUrl)
};
httpClientHandler.PreAuthenticate = true;

var test = client.GetAsync(testUrl).Result;

Console.WriteLine(test);

但它不适用于我的mac。我收到未经授权的 401。两者都使用相同的硬接线连接。这适用于我的mac:

curl --ntlm --user "DOMAINNAME\USERNAME" "https://TFSURL/DefaultCollection/_apis/tfvc/changesets/1234/changes?api-version=2.2"

所以这排除了连接性问题,我想。我错过了我需要在我的 Mac 上做的事情吗?任何人都可以指出一些文档或方法来解决这两个请求在最低级别所做的事情,看看是否有区别?

4

1 回答 1

2

好吧,最后一些 google-foo 让我到达了那里。用于 linux/mac 的 dotnet core 中有一个错误。此问题描述了修复:

https://github.com/dotnet/corefx/issues/25988#issuecomment-412534360

它与使用 Kerberos 和 NTLM 身份验证方法的主机有关。

下面实现:

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);

Console.WriteLine("Type in your DOMAIN password:");
var pass = GetPassword(); //command line secure string magic from SO
var networkCredential = new NetworkCredential("USERNAME", pass, "DOMAINNAME");
string tfsDefaultCollection = "https://TFSURL/DefaultCollection";

string testUrl = $"{tfsDefaultCollection}/_apis/tfvc/changesets/1234/changes?api-version=2.2";

var myCache = new CredentialCache
{
    {
        new Uri(testUrl), "NTLM",
        networkCredential
    }
};

var httpClientHandler = new HttpClientHandler
{
    Credentials = myCache
};

var client = new HttpClient(httpClientHandler)
{
    BaseAddress = new Uri(testUrl)
};
httpClientHandler.PreAuthenticate = true;

var test = client.GetAsync(testUrl).Result;

Console.WriteLine(test);

感谢@dmcgill50 让我走上了正确的谷歌搜索轨道。

于 2019-12-10T17:02:32.277 回答