在 ASP.NET Core 强制实施 HTTPSEnforce HTTPS in ASP.NET Core

作者:Rick AndersonBy Rick Anderson

本文档介绍如何执行以下操作:This document shows how to:

  • 所有请求都需要 HTTPS。Require HTTPS for all requests.
  • 将所有 HTTP 请求重定向到 HTTPS。Redirect all HTTP requests to HTTPS.

任何 API 都不能阻止客户端发送第一个请求上的敏感数据。No API can prevent a client from sending sensitive data on the first request.

警告

API 项目API projects

不要 接收敏感信息的 Web Api 使用 RequireHttpsAttributeDo not use RequireHttpsAttribute on Web APIs that receive sensitive information. RequireHttpsAttribute 使用 HTTP 状态代码将浏览器从 HTTP 重定向到 HTTPS。RequireHttpsAttribute uses HTTP status codes to redirect browsers from HTTP to HTTPS. API 客户端可能不理解或遵循从 HTTP 到 HTTPS 的重定向。API clients may not understand or obey redirects from HTTP to HTTPS. 此类客户端可以通过 HTTP 发送信息。Such clients may send information over HTTP. Web Api 应:Web APIs should either:

  • 不侦听 HTTP。Not listen on HTTP.
  • 关闭状态代码为400的连接 (错误请求) 并且不处理请求。Close the connection with status code 400 (Bad Request) and not serve the request.

HSTS 和 API 项目HSTS and API projects

默认 API 项目不包括 HSTS ,因为 HSTS 通常是仅限浏览器的指令。The default API projects don't include HSTS because HSTS is generally a browser only instruction. 其他调用方(如电话或桌面应用程序) 遵守说明。Other callers, such as phone or desktop apps, do not obey the instruction. 即使是在浏览器中,通过 HTTP 对 API 进行单个身份验证调用也会对不安全网络产生风险。Even within browsers, a single authenticated call to an API over HTTP has risks on insecure networks. 安全方法是将 API 项目配置为仅侦听并通过 HTTPS 进行响应。The secure approach is to configure API projects to only listen to and respond over HTTPS.

警告

API 项目API projects

不要 接收敏感信息的 Web Api 使用 RequireHttpsAttributeDo not use RequireHttpsAttribute on Web APIs that receive sensitive information. RequireHttpsAttribute 使用 HTTP 状态代码将浏览器从 HTTP 重定向到 HTTPS。RequireHttpsAttribute uses HTTP status codes to redirect browsers from HTTP to HTTPS. API 客户端可能不理解或遵循从 HTTP 到 HTTPS 的重定向。API clients may not understand or obey redirects from HTTP to HTTPS. 此类客户端可以通过 HTTP 发送信息。Such clients may send information over HTTP. Web Api 应:Web APIs should either:

  • 不侦听 HTTP。Not listen on HTTP.
  • 关闭状态代码为400的连接 (错误请求) 并且不处理请求。Close the connection with status code 400 (Bad Request) and not serve the request.

需要 HTTPSRequire HTTPS

建议将生产 ASP.NET Core web 应用使用:We recommend that production ASP.NET Core web apps use:

  • HTTPS 重定向中间件 (UseHttpsRedirection) 将 HTTP 请求重定向到 HTTPS。HTTPS Redirection Middleware (UseHttpsRedirection) to redirect HTTP requests to HTTPS.
  • HSTS 中间件 (UseHsts) 将 HTTP 严格传输安全协议 (HSTS) 标头发送到客户端。HSTS Middleware (UseHsts) to send HTTP Strict Transport Security Protocol (HSTS) headers to clients.

备注

使用反向代理配置部署的应用允许代理处理 (HTTPS) 的连接安全。Apps deployed in a reverse proxy configuration allow the proxy to handle connection security (HTTPS). 如果代理还处理 HTTPS 重定向,则无需使用 HTTPS 重定向中间件。If the proxy also handles HTTPS redirection, there's no need to use HTTPS Redirection Middleware. 如果代理服务器还处理写入 HSTS 标头 (例如, IIS 10.0 (1709) 或更高版本) 中的本机 HSTS 支持 ,则该应用程序不要求 HSTS 中间件。If the proxy server also handles writing HSTS headers (for example, native HSTS support in IIS 10.0 (1709) or later), HSTS Middleware isn't required by the app. 有关详细信息,请参阅 在创建项目时选择退出 HTTPS/HSTSFor more information, see Opt-out of HTTPS/HSTS on project creation.

UseHttpsRedirectionUseHttpsRedirection

下面的代码 UseHttpsRedirection 在类中调用 StartupThe following code calls UseHttpsRedirection in the Startup class:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseMvc();
}

前面突出显示的代码:The preceding highlighted code:

建议使用临时重定向,而不是永久重定向。We recommend using temporary redirects rather than permanent redirects. 链接缓存会导致开发环境中的行为不稳定。Link caching can cause unstable behavior in development environments. 如果希望在应用处于非开发环境中时发送永久重定向状态代码,请参阅在 生产中配置永久重定向 部分。If you prefer to send a permanent redirect status code when the app is in a non-Development environment, see the Configure permanent redirects in production section. 我们建议使用 HSTS 来向仅应将安全资源请求发送到应用的客户端发出信号, (仅在生产) 中发送。We recommend using HSTS to signal to clients that only secure resource requests should be sent to the app (only in production).

端口配置Port configuration

端口必须可用于中间件,以将不安全的请求重定向到 HTTPS。A port must be available for the middleware to redirect an insecure request to HTTPS. 如果没有可用的端口:If no port is available:

  • 不会重定向到 HTTPS。Redirection to HTTPS doesn't occur.
  • 中间件记录警告 "无法确定用于重定向的 https 端口"。The middleware logs the warning "Failed to determine the https port for redirect."

使用以下任一方法指定 HTTPS 端口:Specify the HTTPS port using any of the following approaches:

  • 设置 https_port 主机设置Set the https_port host setting:

    • 在 "主机配置" 中。In host configuration.

    • 通过设置 ASPNETCORE_HTTPS_PORT 环境变量。By setting the ASPNETCORE_HTTPS_PORT environment variable.

    • 通过在中添加顶级条目 appsettings.jsonBy adding a top-level entry in appsettings.json:

      {
          "https_port": 443,
          "Logging": {
              "LogLevel": {
                  "Default": "Information",
                  "Microsoft": "Warning",
                  "Microsoft.Hosting.Lifetime": "Information"
              }
          },
          "AllowedHosts": "*"
      }
      
  • 使用 ASPNETCORE_URLS 环境变量指示包含安全方案的端口。Indicate a port with the secure scheme using the ASPNETCORE_URLS environment variable. 环境变量配置服务器。The environment variable configures the server. 中间件通过间接发现 HTTPS 端口 IServerAddressesFeatureThe middleware indirectly discovers the HTTPS port via IServerAddressesFeature. 此方法在反向代理部署中不起作用。This approach doesn't work in reverse proxy deployments.

  • 设置 https_port 主机设置Set the https_port host setting:

    • 在 "主机配置" 中。In host configuration.

    • 通过设置 ASPNETCORE_HTTPS_PORT 环境变量。By setting the ASPNETCORE_HTTPS_PORT environment variable.

    • 通过在中添加顶级条目 appsettings.jsonBy adding a top-level entry in appsettings.json:

      {
          "https_port": 443,
          "Logging": {
              "LogLevel": {
                  "Default": "Warning"
              }
          },
          "AllowedHosts": "*"
      }
      
  • 使用 ASPNETCORE_URLS 环境变量指示包含安全方案的端口。Indicate a port with the secure scheme using the ASPNETCORE_URLS environment variable. 环境变量配置服务器。The environment variable configures the server. 中间件通过间接发现 HTTPS 端口 IServerAddressesFeatureThe middleware indirectly discovers the HTTPS port via IServerAddressesFeature. 此方法在反向代理部署中不起作用。This approach doesn't work in reverse proxy deployments.

  • 在开发中,在 launchsettings.js上 设置 HTTPS URL。In development, set an HTTPS URL in launchsettings.json. 当使用 IIS Express 时,启用 HTTPS。Enable HTTPS when IIS Express is used.

  • Kestrel 服务器或 HTTP.sys 服务器的面向公众的边缘部署配置 HTTPS URL 终结点。Configure an HTTPS URL endpoint for a public-facing edge deployment of Kestrel server or HTTP.sys server. 此应用只使用 一个 HTTPS 端口Only one HTTPS port is used by the app. 中间件通过发现端口 IServerAddressesFeatureThe middleware discovers the port via IServerAddressesFeature.

备注

当应用在反向代理配置中运行时, IServerAddressesFeature 不可用。When an app is run in a reverse proxy configuration, IServerAddressesFeature isn't available. 使用本部分中所述的其他方法之一设置端口。Set the port using one of the other approaches described in this section.

Edge 部署Edge deployments

当 Kestrel 或 HTTP.sys 用作面向公众的边缘服务器时,必须将 Kestrel 或 HTTP.sys 配置为侦听两者:When Kestrel or HTTP.sys is used as a public-facing edge server, Kestrel or HTTP.sys must be configured to listen on both:

  • 重定向客户端的安全端口 (通常是443在生产和5001开发) 。The secure port where the client is redirected (typically, 443 in production and 5001 in development).
  • 在生产环境中,80 (通常为,开发5000环境中) 。The insecure port (typically, 80 in production and 5000 in development).

客户端必须能够访问不安全的端口,以便应用接收不安全的请求,并将客户端重定向到安全端口。The insecure port must be accessible by the client in order for the app to receive an insecure request and redirect the client to the secure port.

有关详细信息,请参阅 Kestrel 终结点配置ASP.NET Core 中的 HTTP.sys Web 服务器实现For more information, see Kestrel endpoint configuration or ASP.NET Core 中的 HTTP.sys Web 服务器实现.

部署方案Deployment scenarios

客户端和服务器之间的任何防火墙都必须为流量打开通信端口。Any firewall between the client and server must also have communication ports open for traffic.

如果在反向代理配置中转发请求,请在调用 HTTPS 重定向中间件前使用 转发的标头中间件If requests are forwarded in a reverse proxy configuration, use Forwarded Headers Middleware before calling HTTPS Redirection Middleware. 转发的标头中间件 Request.Scheme 使用 X-Forwarded-Proto 标头更新。Forwarded Headers Middleware updates the Request.Scheme, using the X-Forwarded-Proto header. 中间件允许重定向 Uri 和其他安全策略正常工作。The middleware permits redirect URIs and other security policies to work correctly. 当未使用转发的标头中间件时,后端应用程序可能无法接收正确的方案并最终出现在重定向循环中。When Forwarded Headers Middleware isn't used, the backend app might not receive the correct scheme and end up in a redirect loop. 常见的最终用户错误消息是发生了太多的重定向。A common end user error message is that too many redirects have occurred.

部署到 Azure App Service 时,请按照 教程:将现有的自定义 SSL 证书绑定到 Azure Web 应用中的指导进行操作。When deploying to Azure App Service, follow the guidance in Tutorial: Bind an existing custom SSL certificate to Azure Web Apps.

选项Options

以下突出显示的代码调用 AddHttpsRedirection 来配置中间件选项:The following highlighted code calls AddHttpsRedirection to configure middleware options:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(60);
        options.ExcludedHosts.Add("example.com");
        options.ExcludedHosts.Add("www.example.com");
    });

    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
        options.HttpsPort = 5001;
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(60);
        options.ExcludedHosts.Add("example.com");
        options.ExcludedHosts.Add("www.example.com");
    });

    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
        options.HttpsPort = 5001;
    });
}

AddHttpsRedirection只有在更改或的值时,才需要调用 HttpsPort RedirectStatusCodeCalling AddHttpsRedirection is only necessary to change the values of HttpsPort or RedirectStatusCode.

前面突出显示的代码:The preceding highlighted code:

在生产环境中配置永久重定向Configure permanent redirects in production

中间件默认为通过所有重定向发送 Status307TemporaryRedirectThe middleware defaults to sending a Status307TemporaryRedirect with all redirects. 如果希望在应用处于非开发环境中时发送永久重定向状态代码,请在非开发环境的条件检查中包装中间件选项配置。If you prefer to send a permanent redirect status code when the app is in a non-Development environment, wrap the middleware options configuration in a conditional check for a non-Development environment.

Startup.cs 中配置服务时:When configuring services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // IWebHostEnvironment (stored in _env) is injected into the Startup class.
    if (!_env.IsDevelopment())
    {
        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
            options.HttpsPort = 443;
        });
    }
}

Startup.cs 中配置服务时:When configuring services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // IHostingEnvironment (stored in _env) is injected into the Startup class.
    if (!_env.IsDevelopment())
    {
        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
            options.HttpsPort = 443;
        });
    }
}

HTTPS 重定向中间件备用方法HTTPS Redirection Middleware alternative approach

() 使用 HTTPS 重定向中间件的替代方法 UseHttpsRedirection 是使用 URL 重写中间件 (AddRedirectToHttps) 。An alternative to using HTTPS Redirection Middleware (UseHttpsRedirection) is to use URL Rewriting Middleware (AddRedirectToHttps). AddRedirectToHttps 执行重定向时,还可以设置状态代码和端口。AddRedirectToHttps can also set the status code and port when the redirect is executed. 有关详细信息,请参阅 URL 重写中间件For more information, see URL Rewriting Middleware.

在不需要其他重定向规则的情况下重定向到 HTTPS 时,我们建议使用 HTTPS 重定向中间件 (UseHttpsRedirection 本主题中所述) 。When redirecting to HTTPS without the requirement for additional redirect rules, we recommend using HTTPS Redirection Middleware (UseHttpsRedirection) described in this topic.

HTTP 严格传输安全协议 (HSTS) HTTP Strict Transport Security Protocol (HSTS)

根据 OWASPHTTP 严格传输安全 (HSTS) 是通过使用响应标头由 web 应用指定的选择加入安全增强功能。Per OWASP, HTTP Strict Transport Security (HSTS) is an opt-in security enhancement that's specified by a web app through the use of a response header. 支持 HSTS 的浏览器 收到此标头时:When a browser that supports HSTS receives this header:

  • 浏览器存储域的配置,阻止通过 HTTP 发送任何通信。The browser stores configuration for the domain that prevents sending any communication over HTTP. 浏览器强制通过 HTTPS 进行的所有通信。The browser forces all communication over HTTPS.
  • 浏览器阻止用户使用不受信任或无效的证书。The browser prevents the user from using untrusted or invalid certificates. 浏览器将禁用允许用户暂时信任此类证书的提示。The browser disables prompts that allow a user to temporarily trust such a certificate.

由于 HSTS 是由客户端强制执行的,因此存在一些限制:Because HSTS is enforced by the client, it has some limitations:

  • 客户端必须支持 HSTS。The client must support HSTS.
  • HSTS 需要至少一个成功的 HTTPS 请求才能建立 HSTS 策略。HSTS requires at least one successful HTTPS request to establish the HSTS policy.
  • 应用程序必须检查每个 HTTP 请求并重定向或拒绝 HTTP 请求。The application must check every HTTP request and redirect or reject the HTTP request.

ASP.NET Core 2.1 和更高版本通过 UseHsts 扩展方法实现 HSTS。ASP.NET Core 2.1 and later implements HSTS with the UseHsts extension method. UseHsts当应用未处于开发模式时,以下代码将调用:The following code calls UseHsts when the app isn't in development mode:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapRazorPages();
    });
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseMvc();
}

UseHsts 不建议在开发中使用,因为 HSTS 设置通过浏览器高度可缓存。UseHsts isn't recommended in development because the HSTS settings are highly cacheable by browsers. 默认情况下,不 UseHsts 包括本地环回地址。By default, UseHsts excludes the local loopback address.

对于第一次实现 HTTPS 的生产环境,请使用其中一种方法将初始HstsOptions设置为较小的值。 TimeSpanFor production environments that are implementing HTTPS for the first time, set the initial HstsOptions.MaxAge to a small value using one of the TimeSpan methods. 将值从小时设置为不超过一天,以防需要将 HTTPS 基础结构还原到 HTTP。Set the value from hours to no more than a single day in case you need to revert the HTTPS infrastructure to HTTP. 在你确信 HTTPS 配置的可持续性后,请增加 HSTS max-age 值; 一个常用值为一年。After you're confident in the sustainability of the HTTPS configuration, increase the HSTS max-age value; a commonly used value is one year.

下面的代码:The following code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(60);
        options.ExcludedHosts.Add("example.com");
        options.ExcludedHosts.Add("www.example.com");
    });

    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
        options.HttpsPort = 5001;
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddHsts(options =>
    {
        options.Preload = true;
        options.IncludeSubDomains = true;
        options.MaxAge = TimeSpan.FromDays(60);
        options.ExcludedHosts.Add("example.com");
        options.ExcludedHosts.Add("www.example.com");
    });

    services.AddHttpsRedirection(options =>
    {
        options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
        options.HttpsPort = 5001;
    });
}
  • 设置标头的预载参数 Strict-Transport-SecuritySets the preload parameter of the Strict-Transport-Security header. 预加载不属于 RFC HSTS 规范,但 web 浏览器支持在全新安装时预加载 HSTS 站点。Preload isn't part of the RFC HSTS specification, but is supported by web browsers to preload HSTS sites on fresh install. 有关详细信息,请参阅 https://hstspreload.org/For more information, see https://hstspreload.org/.
  • 启用 includeSubDomain,这会将 HSTS 策略应用到托管子域。Enables includeSubDomain, which applies the HSTS policy to Host subdomains.
  • max-age 标头的参数显式设置 Strict-Transport-Security 为60天。Explicitly sets the max-age parameter of the Strict-Transport-Security header to 60 days. 如果未设置,则默认值为30天。If not set, defaults to 30 days. 有关详细信息,请参阅 最大期限指令For more information, see the max-age directive.
  • 添加 example.com 到要排除的主机列表。Adds example.com to the list of hosts to exclude.

UseHsts 排除以下环回主机:UseHsts excludes the following loopback hosts:

  • localhost : IPv4 环回地址。localhost : The IPv4 loopback address.
  • 127.0.0.1 : IPv4 环回地址。127.0.0.1 : The IPv4 loopback address.
  • [::1] : IPv6 环回地址。[::1] : The IPv6 loopback address.

在项目创建时选择退出 HTTPS/HSTSOpt-out of HTTPS/HSTS on project creation

在某些后端服务方案中,如果在网络面向公众的边缘处理连接安全,则不需要在每个节点上配置连接安全性。In some backend service scenarios where connection security is handled at the public-facing edge of the network, configuring connection security at each node isn't required. 从 Visual Studio 中的模板或从 dotnet new 命令生成的 Web 应用启用 HTTPS 重定向HSTSWeb apps that are generated from the templates in Visual Studio or from the dotnet new command enable HTTPS redirection and HSTS. 对于不需要这些方案的部署,可以从模板创建应用时选择退出 HTTPS/HSTS。For deployments that don't require these scenarios, you can opt-out of HTTPS/HSTS when the app is created from the template.

选择退出 HTTPS/HSTS:To opt-out of HTTPS/HSTS:

取消选中 " 为 HTTPS 配置 " 复选框。Uncheck the Configure for HTTPS check box.

"新建 ASP.NET Core Web 应用程序" 对话框,其中显示未选择 "配置为 HTTPS" 复选框。

"新建 ASP.NET Core Web 应用程序" 对话框,其中显示未选择 "配置为 HTTPS" 复选框。

信任 Windows 和 macOS 上的 ASP.NET Core HTTPS 开发证书Trust the ASP.NET Core HTTPS development certificate on Windows and macOS

.NET Core SDK 包含 HTTPS 开发证书。The .NET Core SDK includes an HTTPS development certificate. 此证书作为首次运行体验的一部分进行安装。The certificate is installed as part of the first-run experience. 例如,会 dotnet --info 生成以下输出的变体:For example, dotnet --info produces a variation of the following output:

ASP.NET Core
------------
Successfully installed the ASP.NET Core HTTPS Development Certificate.
To trust the certificate run 'dotnet dev-certs https --trust' (Windows and macOS only).
For establishing trust on other platforms refer to the platform specific documentation.
For more information on configuring HTTPS see https://go.microsoft.com/fwlink/?linkid=848054.

安装 .NET Core SDK 会将 ASP.NET Core HTTPS 开发证书安装到本地用户证书存储。Installing the .NET Core SDK installs the ASP.NET Core HTTPS development certificate to the local user certificate store. 已安装证书,但该证书不受信任。The certificate has been installed, but it's not trusted. 若要信任该证书,请执行一次性步骤来运行 dotnet dev-certs 工具:To trust the certificate, perform the one-time step to run the dotnet dev-certs tool:

dotnet dev-certs https --trust

下面的命令提供有关 dev-certs 工具的帮助:The following command provides help on the dev-certs tool:

dotnet dev-certs https --help

如何为 Docker 设置开发人员证书How to set up a developer certificate for Docker

请参阅此 GitHub 问题See this GitHub issue.

在 Linux 上信任 HTTPS 证书Trust HTTPS certificate on Linux

有关 Linux 的说明,请参阅分发文档。For instructions on Linux, refer to the distribution documentation.

从适用于 Linux 的 Windows 子系统信任 HTTPS 证书Trust HTTPS certificate from Windows Subsystem for Linux

适用于 Linux 的 Windows 子系统 (WSL) 生成一个 HTTPS 自签名证书。若要将 Windows 证书存储配置为信任 WSL 证书,请执行以下操作:The Windows Subsystem for Linux (WSL) generates an HTTPS self-signed cert. To configure the Windows certificate store to trust the WSL certificate:

  • 运行以下命令以导出 WSL 生成的证书:Run the following command to export the WSL-generated certificate:

    dotnet dev-certs https -ep %USERPROFILE%\.aspnet\https\aspnetapp.pfx -p <cryptic-password>
    
  • 在 WSL 窗口中运行以下命令:In a WSL window, run the following command:

      ASPNETCORE_Kestrel__Certificates__Default__Password="<cryptic-password>" 
      ASPNETCORE_Kestrel__Certificates__Default__Path=/mnt/c/Users/user-name/.aspnet/https/aspnetapp.pfx
      dotnet watch run
    

    上述命令将设置环境变量,以便 Linux 使用 Windows 受信任的证书。The preceding command sets the environment variables so Linux uses the Windows trusted certificate.

排查证书问题Troubleshoot certificate problems

本部分提供了在 安装和信任ASP.NET Core HTTPS 开发证书时,但仍会出现浏览器警告,指出该证书不受信任。This section provides help when the ASP.NET Core HTTPS development certificate has been installed and trusted, but you still have browser warnings that the certificate is not trusted. Kestrel使用 ASP.NET Core HTTPS 开发证书。The ASP.NET Core HTTPS development certificate is used by Kestrel.

若要修复 IIS Express 证书,请参阅 此 Stackoverflow 问题。To repair the IIS Express certificate, see this Stackoverflow issue.

所有平台-证书不受信任All platforms - certificate not trusted

运行以下命令:Run the following commands:

dotnet dev-certs https --clean
dotnet dev-certs https --trust

关闭所有打开的浏览器实例。Close any browser instances open. 在应用程序中打开新的浏览器窗口。Open a new browser window to app. 证书信任由浏览器进行缓存。Certificate trust is cached by browsers.

前面的命令解决了大多数浏览器信任问题。The preceding commands solve most browser trust issues. 如果浏览器仍不信任证书,请遵循以下特定于平台的建议。If the browser is still not trusting the certificate, follow the platform-specific suggestions that follow.

Docker-证书不受信任Docker - certificate not trusted

  • 删除 C:\Users { USER} \AppData\Roaming\ASP.NET\Https 文件夹。Delete the C:\Users{USER}\AppData\Roaming\ASP.NET\Https folder.
  • 清理解决方案。Clean the solution. 删除 bin 和 obj 文件夹。Delete the bin and obj folders.
  • 重新启动开发工具。Restart the development tool. 例如,Visual Studio、Visual Studio Code 或 Visual Studio for Mac。For example, Visual Studio, Visual Studio Code, or Visual Studio for Mac.

Windows-证书不受信任Windows - certificate not trusted

  • 检查证书存储区中的证书。Check the certificates in the certificate store. localhost在和中应有一个具有 ASP.NET Core HTTPS development certificate 友好名称的证书 Current User > Personal > Certificates``Current User > Trusted root certification authorities > CertificatesThere should be a localhost certificate with the ASP.NET Core HTTPS development certificate friendly name both under Current User > Personal > Certificates and Current User > Trusted root certification authorities > Certificates
  • 从 "个人" 和 "受信任的根证书颁发机构" 中删除所有找到的证书。Remove all the found certificates from both Personal and Trusted root certification authorities. 请勿 删除 IIS Express localhost 证书。Do not remove the IIS Express localhost certificate.
  • 运行以下命令:Run the following commands:
dotnet dev-certs https --clean
dotnet dev-certs https --trust

关闭所有打开的浏览器实例。Close any browser instances open. 在应用程序中打开新的浏览器窗口。Open a new browser window to app.

OS X-证书不受信任OS X - certificate not trusted

  • 打开密钥链访问。Open KeyChain Access.
  • 选择系统密钥链。Select the System keychain.
  • 检查是否存在 localhost 证书。Check for the presence of a localhost certificate.
  • 检查它是否 + 在图标上包含符号,以指示其对所有用户都是受信任的。Check that it contains a + symbol on the icon to indicate it's trusted for all users.
  • 从系统密钥链中删除证书。Remove the certificate from the system keychain.
  • 运行以下命令:Run the following commands:
dotnet dev-certs https --clean
dotnet dev-certs https --trust

关闭所有打开的浏览器实例。Close any browser instances open. 在应用程序中打开新的浏览器窗口。Open a new browser window to app.

请参阅 HTTPS 错误,使用 IIS Express (dotnet/AspNetCore #16892) 用于排查 Visual Studio 的证书问题。See HTTPS Error using IIS Express (dotnet/AspNetCore #16892) for troubleshooting certificate issues with Visual Studio.

用于 Visual Studio 的 IIS Express SSL 证书IIS Express SSL certificate used with Visual Studio

若要解决 IIS Express 证书的问题,请从 Visual Studio 安装程序中选择 " 修复 "。To fix problems with the IIS Express certificate, select Repair from the Visual Studio installer. 有关详细信息,请参阅此 GitHub 问题For more information, see this GitHub issue.

Firefox SEC_ERROR_INADEQUATE_KEY_USAGE 证书错误Firefox SEC_ERROR_INADEQUATE_KEY_USAGE certificate error

Firefox 浏览器使用自己的证书存储区,因此不信任 IIS ExpressKestrel 开发人员证书。The Firefox browser uses it's own certificate store, and therefore doesn't trust the IIS Express or Kestrel developer certificates.

若要将 Firefox 与 IIS Express 或 Kestrel 一起使用,请设置 security.enterprise_roots.enabled = trueTo use Firefox with IIS Express or Kestrel, set security.enterprise_roots.enabled = true

  1. about:config在 FireFox 浏览器中输入。Enter about:config in the FireFox browser.
  2. 如果接受风险,则选择 "接受风险并继续"Select Accept the Risk and Continue if you accept the risk.
  3. 选择 全部显示Select Show All
  4. 字符集 security.enterprise_roots.enabled = trueSet security.enterprise_roots.enabled = true
  5. 退出并重新启动 FirefoxExit and restart Firefox

有关详细信息,请参阅 在 Firefox 中 (CAs) 设置证书颁发机构For more information, see Setting Up Certificate Authorities (CAs) in Firefox.

其他信息Additional information