简体   繁体   English

无法从控制台应用程序向Web API发送/接收客户端证书

[英]Fail to send/receive Client Certificate from Console App to web api

I created a Web Api to accept a client certificate. 我创建了一个Web Api以接受客户端证书。
I am calling the web api from a console app using the following code. 我正在使用以下代码从console app调用Web API。

var uri = new Uri("https://myservice.azurewebsites.net/api/values");

var handler = new WebRequestHandler();

handler.ClientCertificateOptions = ClientCertificateOption.Manual;
var certResults = new X509Store(StoreLocation.LocalMachine);
var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

try
{
    certStore.Open(OpenFlags.ReadOnly);
}
catch (Exception)
{
    Console.WriteLine("Unable to access Certificate store");
}

var thumbprint = "<<self signed cert thumbprint>>";
var certCollection = certStore.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false);
certStore.Close();

HttpClient client = new HttpClient(handler);
if (certCollection.Count > 0)
{
    handler.ClientCertificates.Add(certCollection[0]);
    client.DefaultRequestHeaders.Add("Thumbprint", certCollection[0].Thumbprint);
}

var result = client.GetAsync(uri).GetAwaiter().GetResult();

Console.WriteLine($"status: {result.StatusCode}");    
Console.WriteLine($"content: {result.Content.ReadAsStringAsync().GetAwaiter().GetResult()}");    
Console.ReadLine();
}

On the server side, I added a middleware to get the certificate details. 在服务器端,我添加了一个中间件来获取证书详细信息。

{
    //var certHeader = context.Request.Headers["X-ARR-ClientCert"];

    var certificate = context.Connection.ClientCertificate;
    if (certificate != null)
    {
        try
        {
            //var clientCertBytes = Convert.FromBase64String(certHeader);
            //var certificate = new X509Certificate2(clientCertBytes);

            bool isValidCert = IsValidClientCertificate(certificate);
            if (isValidCert)
            {
                await _next.Invoke(context);
            }
            else
            {
                _logger.LogError("Certificate is not valid");
                context.Response.StatusCode = 403;
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex.Message, ex);
            await context.Response.WriteAsync(ex.Message);
            context.Response.StatusCode = 403;
        }
    }
    else
    {
        _logger.LogError("X-ARR-ClientCert header is missing");
        context.Response.StatusCode = 403;
    }
}

I tried running it on the local machine and on Azure App Services. 我尝试在本地计算机和Azure App Services上运行它。 I set the flag clientCertEnabled to true in resources.azure.com . 我在resources.azure.com中将标志clientCertEnabled设置为true Web Api is SSL enabled. Web Api已启用SSL。

But the certificate is always coming as null in both 但是,证书在两种情况下都始终为null
var certHeader = context.Request.Headers["X-ARR-ClientCert"]; and var certificate = context.Connection.ClientCertificate; var certificate = context.Connection.ClientCertificate; .

What am I doing wrong here? 我在这里做错了什么?

Thanks in advance. 提前致谢。

Was reasearching some of this stuff myself and seeing your question, I wonder if you are having one of the issues described in the link Securing ASP.NET WebAPI using Client Certificates 我自己在研究其中的一些内容并看到了您的问题,我想知道您是否遇到了使用客户端证书保护ASP.NET WebAPI链接中描述的问题之一。

Specifically: 特别:

4 Add MyPersonalCA.cer to Local Machine -> Truted Root Certificate Authorities. 4将MyPersonalCA.cer添加到本地计算机->根证书颁发机构。 This is key, espcially while you are developing and want to try things. 这是关键,尤其是在您正在开发并且想尝试的时候。 If you don't do it, Request.ClientCertificate won't be populated because the cert chain is untrusted. 如果您不这样做,则不会填充Request.ClientCertificate,因为证书链不受信任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用来自另一个Web API的客户端证书调用Web API - Calling web api with client certificate from another web api 如何从Xamarin Android App(客户端)向Dot Net Web API(服务器)发送字符串内容? - How do i send a string content to Dot Net Web API(Server) from Xamarin Android App(Client)? 从客户端应用程序调用Web API - Call web API from client app 来自控制台应用程序或Android应用程序的Https Web API - Https Web API from console app or android app 如何在Web API中发送和接收Complex对象 - How to send and receive Complex object in web api 在 .NET 控制台客户端应用程序中使用 ASP.NET Core SignalR 从 Azure SignalR 接收消息 - Using ASP.NET Core SignalR in .NET Console Client App to Receive Messages from Azure SignalR 将字符串作为 JSON object 从 web Z8A5DA52ED126447D359E70C05721A8 发送到客户端 - Send a String as JSON object from web api to the client 从Web API调用中的控制台应用程序获取响应 - Getting response from console app within web api call 将对象数据从控制台应用程序发布到Web API - Posting Object Data from Console App to Web API 从自托管的WEB API控制台应用程序返回jsonp - Return jsonp from self hosted WEB API Console app
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM