在 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 apps 使用生產環境: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 Strict 傳輸安全性通訊協定 (HSTS) 標頭傳送給用戶端。HSTS Middleware (UseHsts) to send HTTP Strict Transport Security Protocol (HSTS) headers to clients.

注意

部署在反向 proxy 設定中的應用程式,可讓 proxy 處理 (HTTPS) 的連線安全性。Apps deployed in a reverse proxy configuration allow the proxy to handle connection security (HTTPS). 如果 proxy 也處理 HTTPS 重新導向,則不需要使用 HTTPS 重新導向中介軟體。If the proxy also handles HTTPS redirection, there's no need to use HTTPS Redirection Middleware. 如果 proxy 伺服器也會處理寫入 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. 這種方法不適用於反向 proxy 部署。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. 這種方法不適用於反向 proxy 部署。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 server 或 HTTP.sys server 的公眾面向邊緣部署設定 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.

注意

當應用程式在反向 proxy 設定中執行時, 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 用作公眾對應的 edge server 時,必須將 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 endpoint configurationASP.NET Core 中的 HTTP.sys 網頁伺服器實作For more information, see Kestrel endpoint configuration or ASP.NET Core 中的 HTTP.sys 網頁伺服器實作.

部署案例Deployment scenarios

用戶端與伺服器之間的任何防火牆也必須針對流量開啟通訊埠。Any firewall between the client and server must also have communication ports open for traffic.

如果在反向 proxy 設定中轉送要求,請在呼叫 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 Apps中的指導方針。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 Strict Transport Security Protocol (HSTS) HTTP Strict Transport Security Protocol (HSTS)

根據 OWASPHTTP Strict TRANSPORT Security (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 和更新版本會使用擴充方法來執行 HSTS UseHstsASP.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 規格的一部分,但是網頁瀏覽器支援在全新安裝時預先載入 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] 核取方塊。](enforcing-ssl/_static/out-vs2019.png)

![新的 ASP.NET Core Web 應用程式] 對話方塊,顯示未選取的 [設定 HTTPS] 核取方塊。](enforcing-ssl/_static/out.png)

信任 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.

信任 Windows 子系統 Linux 版的 HTTPS 憑證Trust HTTPS certificate from Windows Subsystem for Linux

Windows 子系統 Linux 版 (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

  • 開啟 [KeyChain 存取]。Open KeyChain Access.
  • 選取 [系統 keychain]。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.
  • 從系統 keychain 移除憑證。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.

請參閱 使用 IIS Express (dotnet/AspNetCore #16892) 進行 Visual Studio 的憑證問題疑難排解的 HTTPS 錯誤。See HTTPS Error using IIS Express (dotnet/AspNetCore #16892) for troubleshooting certificate issues with Visual Studio.

IIS Express 與 Visual Studio 搭配使用的 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.

若要搭配 IIS Express 或 Kestrel 使用 Firefox,請設定 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