我正在使用Owin
自行托管网络应用程序。
服务器上定义的身份验证方案如下:
HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;
我的客户端代码如下:
using (var webRequestHandler = new WebRequestHandler {UseDefaultCredentials = true})
using (var httpClient = new HttpClient(webRequestHandler))
{
var responseCode = httpClient.PostAsync("https://server:443/myapi/dosomething/", null).Result.StatusCode;
Console.WriteLine(responseCode == HttpStatusCode.OK ? "Success" : "Failure");
}
当客户端计算机上的登录用户是服务器机器已知的用户时,此功能非常有用。
例如,当客户端的计算机未加入域并且客户端由本地用户运行时,问题就开始了。在这种情况下,我已经扩展了我的客户端,如下所示:
HttpStatusCode responseCode;
using (var webRequestHandler = new WebRequestHandler {UseDefaultCredentials = true})
using (var httpClient = new HttpClient(webRequestHandler))
{
responseCode = httpClient.PostAsync("https://server:443/myapi/dosomething/", null).Result.StatusCode;
}
if (responseCode == HttpStatusCode.Unauthorized)
{
string username;
string password;
// prompt user for credentials and store them at the above variables
using (var webRequestHandler = new WebRequestHandler { Credentials = new NetworkCredential(username, password)})
using (var httpClient = new HttpClient(webRequestHandler))
{
responseCode = httpClient.PostAsync("https://server:443/myapi/dosomething/", null).Result.StatusCode;
}
}
Console.WriteLine(responseCode == HttpStatusCode.OK ? "Success" : "Failure");
这解决了它,但我仅限于使用用户名/密码执行回退身份验证。
我的问题是我需要支持智能卡身份验证以及用户名/密码身份验证。
答案 0 :(得分:1)
假设"智能卡身份验证"通过客户端证书完成,您可以通过以下方式启用此功能:
配置HttpClient
以自动选择证书
var client = new HttpClient(
new HttpClientHandler{
ClientCertificateOptions = ClientCertificateOption.Automatic
});
或通过使用以前选择的证书配置HttpClient
var clientHandler = new WebRequestHandler();
clientHandler.ClientCertificates.Add(cert);
var client = new HttpClient(clientHandler);
其中cert
是具有关联私钥的证书。