为 HTTPS 配置 ASP.NET Core 2.0 Kestrel [英] Configure ASP.NET Core 2.0 Kestrel for HTTPS

查看:34
本文介绍了为 HTTPS 配置 ASP.NET Core 2.0 Kestrel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL;DR 目前使用 ASP.NET Core 2.0 设置 HTTPS 的正确方法是什么?

TL;DR What is today the correct way to setup HTTPS with ASP.NET Core 2.0?

我想将我的项目配置为使用 https 和证书,就像他们在 构建 2017.我尝试了几种设置,但没有任何效果.经过一番研究,我更加困惑了.似乎有很多方法可以配置 URL 和端口……我见过 appsettings.jsonhosting.json,通过代码,在 launchsettings.json 我们还可以设置 URL 和端口.

I would like to configure my project to use https and a certificate like they have shown at BUILD 2017. I have tried several settings but nothing worked. After some research, I am even more confused. It seems that there are many ways to configure URLs and ports… I have seen appsettings.json, hosting.json, via code, and in launchsettings.json we can also set the URL and port.

有没有标准"的方法来做到这一点?

Is there a "standard" way to do it?

这是我的appsettings.development.json

{
  "Kestrel": {
    "Endpoints": {
      "Localhost": {
        "Address": "127.0.0.1",
        "Port": "40000"
      },
      "LocalhostWithHttps": {
        "Address": "127.0.0.1",
        "Port": "40001",
        "Certificate": {
          "HTTPS": {
            "Source": "Store",
            "StoreLocation": "LocalMachine",
            "StoreName": "My",
            "Subject": "CN=localhost",
            "AllowInvalid": true
          }
        }
      }
    }
  }
}

但是当我从命令行使用 dotnet run 启动或从 Visual Studio 启动调试器时,它总是从 launchsettings.json 获取 url 和端口.

But it always takes the url and the port from launchsettings.json when I start from the command line with dotnet run or when I start with the debugger from Visual Studio.

这是我的 Program.csStartup.cs

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

public class Startup
{
    public IConfiguration Configuration { get; }
    public string Authority { get; set; } = "Authority";
    public string ClientId { get; set; } = "ClientId";

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<MvcOptions>(options => options.Filters.Add(new RequireHttpsAttribute()));

        JsonConvert.DefaultSettings = () => new JsonSerializerSettings() {
            NullValueHandling = NullValueHandling.Ignore
        };

        services.AddSingleton<IRepository, AzureSqlRepository>(x => new AzureSqlRepository(Configuration.GetConnectionString("DefaultConnection")));
        services.AddSingleton<ISearchSplitService, SearchSplitService>();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => new JwtBearerOptions {
                Authority = this.Authority,
                Audience = this.ClientId
        });

        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions() { HotModuleReplacement = true, ReactHotModuleReplacement = true, HotModuleReplacementEndpoint = "/dist/__webpack_hmr" });
        }

        app.UseStaticFiles();
        app.UseAuthentication();

        app.UseMvc(routes => {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new { controller = "Home", action = "Index" });
        });
    }
}

正如我所说,我无法让它在任何星座中工作.现在使用 ASP.NET Core 2.0 设置 HTTPS 的正确方法是什么?

As I have said, I was not able to get it working in any constallation. What is today the correct way to setup HTTPS with ASP.NET Core 2.0?

推荐答案

不幸的是,在 ASP.NET Core 2.0 发布之前的各种视频或教程中已经展示了基于配置的设置 HTTPS 的方式.t 使其成为最终版本.

Unfortunately, the way of configuration-based way of setting up HTTPS that has been shown in various videos or tutorials before the launch of ASP.NET Core 2.0 didn’t make it into the final release.

对于 2.0,配置 HTTPS 的唯一方法是在代码中,通过显式设置 Kestrel 侦听器,如在本公告中,并使用ListenOptions.UseHttps 启用 HTTPS:

For 2.0, the only way to configure HTTPS is in code, by explicitly setting up the Kestrel listeners, as explained in this announcement, and using ListenOptions.UseHttps to enable HTTPS:

var host = new WebHostBuilder()
    .UseKestrel(options =>
    {
        options.ListenAnyIP(443, listenOptions => 
        {
            listenOptions.UseHttps("server.pfx", "password");
        });
    })
    .UseStartup<Startup>()
    .Build();

不幸的是,在发布时,官方文档没有正确涵盖这一点,并宣传了未实现的基于配置的方式.此后已修复.

Unfortunately, at the time of release, the official documentation also did not cover this properly and advertised the configuration-based way that wasn’t implemented. This has been fixed since.

从 ASP.NET Core 2.1 开始,如最初承诺的那样,基于配置的 HTTPS 设置将成为可能.这可能看起来像这样,正如 GitHub 上的 Tratcher 所述:

Starting with ASP.NET Core 2.1, configuration based HTTPS setup will be possible, as originally promised. This will likely look like this, as explained by Tratcher on GitHub:

"Kestrel": {
  "Endpoints": {
    "HTTPS": {
      "Url": "https://*:443",
      "Certificate": {
        "Path": "server.pfx",
        "Password": "password"
      }
    }
  }
}

<小时>

在您的特定示例中,基于代码的配置如下所示.请注意,如果您不想使用证书文件,则需要先从证书存储中手动检索证书.


In your particular example, the code-based configuration would look like the following. Note that if you don’t want to use a certificate file, you need to manually retrieve the certificate from the certificate store first.

.UseKestrel(options =>
{
    // listen for HTTP
    options.ListenLocalhost(40000);

    // retrieve certificate from store
    using (var store = new X509Store(StoreName.My))
    {
        store.Open(OpenFlags.ReadOnly);
        var certs = store.Certificates.Find(X509FindType.FindBySubjectName, 
            "localhost", false);
        if (certs.Count > 0)
        {
            var certificate = certs[0];

            // listen for HTTPS
            options.ListenLocalhost(40001, listenOptions =>
            {
                listenOptions.UseHttps(certificate);
            });
        }
    }
})

这篇关于为 HTTPS 配置 ASP.NET Core 2.0 Kestrel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆