C# 在 ASP.NET 自托管 Web API 上配置 SSL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18443181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 12:13:31  来源:igfitidea点击:

Configuring SSL on ASP.NET Self-Hosted Web API

c#sslasp.net-web-api

提问by insomnium_

I'm creating Self-hosted Web API service. To secure it, I've studied and implemented thisarticle, successfully generated an local SSL Certificate using makecert and my service authenticated and generates tokens fine, if I'm using

我正在创建自托管 Web API 服务。为了保护它,我研究并实现了这篇文章,使用 makecert 成功生成了本地 SSL 证书,并且我的服务经过身份验证并生成令牌很好,如果我正在使用

http://localhost/webapi/authentication/authenticate

link, but when I try to access my service using HTTPS, I get following on Firefox:

链接,但是当我尝试使用 HTTPS 访问我的服务时,我在 Firefox 上得到以下信息:

ssl_error_rx_record_too_long

ssl_error_rx_record_too_long

and for the same request Fiddler shows me:

对于 Fiddler 向我展示的相同请求:

HTTP/1.1 502 Fiddler - Connection Failed Date: Mon, 26 Aug 2013 10:44:27 GMT Content-Type: text/html; charset=UTF-8 Connection: close Timestamp: 13:44:27.433

[Fiddler] The socket connection to localhost failed.
Failed to negotiate HTTPS connection with server.fiddler.network.https> Failed to secure existing connection for localhost. The handshake failed due to an unexpected packet format..

HTTP/1.1 502 Fiddler - 连接失败日期:2013 年 8 月 26 日星期一 10:44:27 GMT 内容类型:text/html;charset=UTF-8 连接:关闭时间戳:13:44:27.433

[Fiddler] 到 localhost 的套接字连接失败。
无法与 server.fiddler.network.https 协商 HTTPS 连接> 无法保护本地主机的现有连接。由于意外的数据包格式,握手失败。

My self-host configuration:

我的自托管配置:

    private HttpSelfHostServer _server;
    private ExtendedHttpsSelfHostConfiguration _config;
    public const string ServiceAddress = "https://localhost/webapi";
    _config = new ExtendedHttpsSelfHostConfiguration(ServiceAddress);
    _server = new HttpSelfHostServer(_config);
    _server.OpenAsync();

where ExtendedHttpSelfHostConfiguration taken from this postis:

这篇文章中获取的 ExtendedHttpSelfHostConfiguration是:

public class ExtendedHttpSelfHostConfiguration : HttpSelfHostConfiguration
{
    public ExtendedHttpSelfHostConfiguration(string baseAddress) : base(baseAddress) { }
    public ExtendedHttpSelfHostConfiguration(Uri baseAddress) : base(baseAddress) { }

    protected override BindingParameterCollection OnConfigureBinding(HttpBinding httpBinding)
    {
        if (BaseAddress.ToString().ToLower().Contains("https://"))
        {
            httpBinding.Security.Mode = HttpBindingSecurityMode.Transport;
        }

        return base.OnConfigureBinding(httpBinding);
    }
}

What I'm missing? Thanks in advance!

我缺少什么?提前致谢!

采纳答案by insomnium_

According to this blog postI've figured out, that I should create an SSL certificate and assign it to specific port (:99 in my case).

根据我发现的这篇博客文章,我应该创建一个 SSL 证书并将其分配给特定端口(在我的情况下为:99)。

I've created locally signed SSL. Then got it's Thumbprintand ApplicationId. Using CMD command netsh(in pre Win7 systems there is an httpcfgtool), I've assigned my certificate to the port

我已经创建了本地签名的 SSL。然后得到它的ThumbprintApplicationId。使用 CMD 命令netsh(在 Win7 系统之前有一个httpcfg工具),我已将我的证书分配给端口

netsh http add sslcert ipport=0.0.0.0:99 certhash=3e49906c01a774c888231e5092077d3d855a6861 appid={2d6059b2-cccb-4a83-ae08-8ce209c2c5c1}, where certhash = SSL Thumbprint, and appid = ApplicationIdI've copied earlier.

netsh http add sslcert ipport=0.0.0.0:99 certhash=3e49906c01a774c888231e5092077d3d855a6861 appid={2d6059b2-cccb-4a83-ae08-8ce209c2c5c1},其中 certhash = SSL Thumbprint和 appid = ApplicationId我之前复制过。

That's it, now I'm able to make HTTPS requests!

就是这样,现在我可以发出 HTTPS 请求了!

回答by Deepak Madheshiya

First approach using Code:

使用代码的第一种方法:

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = actionContext.Request
                .CreateResponse(HttpStatusCode.Found);
            actionContext.Response.Content = new StringContent
                ("<did>Use https instead of http</div>", Encoding.UTF8, "text/html");

            UriBuilder uriBuilder = new UriBuilder(actionContext.Request.RequestUri);
            uriBuilder.Scheme = Uri.UriSchemeHttps;
            uriBuilder.Port = 44337;

            actionContext.Response.Headers.Location = uriBuilder.Uri;
        }
        else
        {
            base.OnAuthorization(actionContext);
        }
    }
}

In the web config file put following code:

在 web 配置文件中输入以下代码:

config.Filters.Add(new RequireHttpsAttribute());

Second approach using Attribute: If you do not want to use the 1st approach, you can decorate the controller class or the action method with RequireHttpsAttribute.

使用 Attribute 的第二种方法:如果不想使用第一种方法,可以使用RequireHttpsAttribute.

回答by Mahmoud

  1. Open IIS
  2. Double Click "Server Certificates"
  3. On the right pane, click "Create Self-Signed Certificate"
  4. Enter name "localhost"
  5. Finish
  1. 打开 IIS
  2. 双击“服务器证书”
  3. 在右侧窗格中,单击“创建自签名证书”
  4. 输入名称“本地主机”
  5. 结束

The certificate will be created with the name you specified, find it.

将使用您指定的名称创建证书,找到它。

  1. Double click the cert, it will open its properties, select 'Thumbprint' and copy the value.
  1. 双击证书,它将打开其属性,选择“指纹”并复制值。

Now you have created the cert, it is time to bind it to the port you are using in the self host. if it was https://localhost:5000

现在您已经创建了证书,是时候将它绑定到您在自主机中使用的端口了。如果是https://localhost:5000

  1. Open elevated CMD
  2. Run this command to bind the certificate you created to the port you are using.
  1. 打开提升的 CMD
  2. 运行此命令将您创建的证书绑定到您正在使用的端口。

netsh http add sslcert ipport=0.0.0.0:5000 certhash=[cert-thumbprint] appid={[App-Id]}

netsh http add sslcert ipport=0.0.0.0:5000 certhash=[cert-thumbprint] appid={[App-Id]}

  1. Replace the [Cert-thumbprint] (including the square brackets) with the value you copied in step 6.
  2. Replace the [app-id] (including the square brackets) is the guid from the app assembly info
  1. 将 [Cert-thumbprint](包括方括号)替换为您在步骤 6 中复制的值。
  2. 替换 [app-id](包括方括号)是来自应用程序集信息的 guid

[assembly: Guid("[app-id]")]

[assembly: Guid("[app-id]")]

You are done!

你完成了!