繁体   English   中英

为HTTPS配置ASP.NET Core 2.0 Kestrel

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

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

我想将我的项目配置为使用https和BUILD 2017所示的证书。 我尝试了几种设置,但没有任何效果。 经过一番研究,我更加困惑。 看来,有很多方法可以配置URL和端口......我看到appsettings.jsonhosting.json ,通过代码,并在launchsettings.json我们还可以设置URL和端口。

有没有“标准”的方式来做到这一点?

这是我的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和端口。

这是我的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的正确方法是什么?

不幸的是,在ASP.NET Core 2.0发布之前的各种视频或教程中已经介绍了基于配置的HTTPS设置方法,但该方法并未进入最终版本。

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

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

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

从ASP.NET Core 2.1开始,可以按照最初的承诺进行基于配置的HTTPS设置。 正如Tratcher在GitHub上所解释的那样,这看起来可能像这样:

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

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

.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);
            });
        }
    }
})

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM