【问题标题】:How to authenticate by smart card as a fallback to windows authentication in httpClint/httpListener如何通过智能卡进行身份验证作为 httpClint/httpListener 中 Windows 身份验证的后备
【发布时间】:2016-07-14 20:09:53
【问题描述】:

我正在使用 Owin 来自托管 Web 应用程序。

服务器端定义的认证方案如下:

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");

这解决了它,但我仅限于使用用户名/密码执行后备身份验证。

我的问题是我需要支持智能卡身份验证以及用户名/密码身份验证。

【问题讨论】:

    标签: c# authentication windows-authentication smartcard dotnet-httpclient


    【解决方案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 是具有关联私钥的证书。

    您可以在 Client Authentication 上阅读更多相关信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-25
      • 2013-03-07
      • 2017-09-18
      • 2015-11-08
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2017-12-29
      相关资源
      最近更新 更多