在 ASP.NET Core 中設定 Windows 驗證Configure Windows Authentication in ASP.NET Core

作者:Scott AddieLuke LathamBy Scott Addie and Luke Latham

Windows 驗證 可以針對 IISHTTP.sys 上裝載的 ASP.NET Core 應用程式設定。Windows Authentication can be configured for ASP.NET Core apps hosted with IIS or HTTP.sys.

Windows 驗證仰賴作業系統來驗證 ASP.NET Core 應用程式的使用者。Windows Authentication relies on the operating system to authenticate users of ASP.NET Core apps. 當您的伺服器在公司網路上執行時,您可以透過 Active Directory 網域身分識別進行 Windows 驗證或透過 Windows 帳戶來識別使用者。You can use Windows Authentication when your server runs on a corporate network using Active Directory domain identities or Windows accounts to identify users. Windows 驗證最適合用於使用者、用戶端應用程式與 Web 伺服器皆屬於相同 Windows 網域的內部網路環境。Windows Authentication is best suited to intranet environments where users, client apps, and web servers belong to the same Windows domain.

啟用 ASP.NET Core 應用程式中的 Windows 驗證Enable Windows Authentication in an ASP.NET Core app

Web 應用程式可透過 Visual Studio 或.NET Core CLI 的範本可以設定為支援 Windows 驗證。The Web Application template available via Visual Studio or the .NET Core CLI can be configured to support Windows Authentication.

新的專案中使用 Windows 驗證應用程式範本Use the Windows Authentication app template for a new project

在 Visual Studio 中:In Visual Studio:

  1. 建立新的專案。Create a new project.
  2. 選取 [ASP.NET Core Web 應用程式]。Select ASP.NET Core Web Application. 選取 [下一步]。Select Next.
  3. 提供的名稱專案名稱欄位。Provide a name in the Project name field. 確認位置項目是否正確,或提供專案的位置。Confirm the Location entry is correct or provide a location for the project. 選取 [建立]。Select Create.
  4. 選取 變更下方驗證Select Change under Authentication.
  5. 變更驗證視窗中,選取Windows 驗證In the Change Authentication window, select Windows Authentication. 選取 [確定]。Select OK.
  6. 選取 [Web 應用程式]。Select Web Application.
  7. 選取 [建立]。Select Create.

執行應用程式。Run the app. 使用者名稱會出現在呈現的應用程式使用者介面。The username appears in the rendered app's user interface.

手動設定現有的專案Manual configuration for an existing project

專案的屬性可讓您以啟用 Windows 驗證並停用匿名驗證:The project's properties allow you to enable Windows Authentication and disable Anonymous Authentication:

  1. 在 Visual Studio 的專案上按一下滑鼠右鍵方案總管,然後選取屬性Right-click the project in Visual Studio's Solution Explorer and select Properties.
  2. 選取 [偵錯] 索引標籤。Select the Debug tab.
  3. 清除核取方塊啟用匿名驗證Clear the check box for Enable Anonymous Authentication.
  4. 選取核取方塊啟用 Windows 驗證Select the check box for Enable Windows Authentication.

或者,設定屬性,在iisSettings的節點launchSettings.json檔案:Alternatively, the properties can be configured in the iisSettings node of the launchSettings.json file:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
        "applicationUrl": "http://localhost:52171/",
        "sslPort": 0
    }
}

當修改現有的專案,請確認專案檔包含的套件參考Microsoft.AspNetCore.App 中繼套件或是 Microsoft.AspNetCore.Authentication NuGet 套件。When modifying an existing project, confirm that the project file includes a package reference for the Microsoft.AspNetCore.App metapackage or the Microsoft.AspNetCore.Authentication NuGet package.

啟用 iis 的 Windows 驗證Enable Windows Authentication with IIS

IIS 會使用ASP.NET Core 模組主機 ASP.NET Core 應用程式。IIS uses the ASP.NET Core Module to host ASP.NET Core apps. Windows 驗證針對透過 IIS web.config檔案。Windows Authentication is configured for IIS via the web.config file. 下列各節將示範如何:The following sections show how to:

  • 提供本機web.config部署應用程式時,請在伺服器啟動 Windows 驗證的檔案。Provide a local web.config file that activates Windows Authentication on the server when the app is deployed.
  • 使用 IIS 管理員設定web.config已經部署到伺服器的 ASP.NET Core 應用程式的檔案。Use the IIS Manager to configure the web.config file of an ASP.NET Core app that has already been deployed to the server.

IIS 組態IIS configuration

如果您尚未這麼做,請啟用 IIS 可裝載 ASP.NET Core 應用程式。If you haven't already done so, enable IIS to host ASP.NET Core apps. 如需詳細資訊,請參閱在使用 IIS 的 Windows 上裝載 ASP.NET CoreFor more information, see 在使用 IIS 的 Windows 上裝載 ASP.NET Core.

啟用 Windows 驗證的 IIS 角色服務。Enable the IIS Role Service for Windows Authentication. 如需詳細資訊,請參閱 < 啟用 IIS 角色服務 (請參閱步驟 2) 中的 Windows 驗證For more information, see Enable Windows Authentication in IIS Role Services (see Step 2).

根據預設,IIS Integration 中介軟體會設定來自動驗證要求。IIS Integration Middleware is configured to automatically authenticate requests by default. 如需詳細資訊,請參閱裝載 ASP.NET Core 與 IIS 的 Windows 上:IIS 選項 (AutomaticAuthentication)For more information, see Host ASP.NET Core on Windows with IIS: IIS options (AutomaticAuthentication).

ASP.NET Core 模組預設設定為轉送至應用程式的 Windows 驗證語彙基元。The ASP.NET Core Module is configured to forward the Windows Authentication token to the app by default. 如需詳細資訊,請參閱ASP.NET Core 模組組態參考:AspNetCore 元素的屬性For more information, see ASP.NET Core Module configuration reference: Attributes of the aspNetCore element.

建立新的 IIS 站台Create a new IIS site

指定的名稱和資料夾,並允許它建立新的應用程式集區。Specify a name and folder and allow it to create a new application pool.

啟用 IIS 中的應用程式的 Windows 驗證Enable Windows Authentication for the app in IIS

使用任一下列其中一個方法:Use either of the following approaches:

使用本機 web.config 檔案的開發後端設定Development-side configuration with a local web.config file

執行下列步驟之前發佈和部署您的專案Perform the following steps before you publish and deploy your project.

新增下列web.config至專案根目錄的檔案:Add the following web.config file to the project root:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <security>
        <authentication>
          <anonymousAuthentication enabled="false" />
          <windowsAuthentication enabled="true" />
        </authentication>
      </security>
    </system.webServer>
  </location>
</configuration>

專案 sdk 的發行時 (不含<IsTransformWebConfigDisabled>屬性設定為true專案檔中),發行web.config檔案包含<location><system.webServer><security><authentication>一節。When the project is published by the SDK (without the <IsTransformWebConfigDisabled> property set to true in the project file), the published web.config file includes the <location><system.webServer><security><authentication> section. 如需詳細資訊<IsTransformWebConfigDisabled>屬性,請參閱在使用 IIS 的 Windows 上裝載 ASP.NET CoreFor more information on the <IsTransformWebConfigDisabled> property, see 在使用 IIS 的 Windows 上裝載 ASP.NET Core.

伺服器端設定使用 IIS 管理員Server-side configuration with the IIS Manager

執行下列步驟之後發佈和部署您的專案Perform the following steps after you publish and deploy your project.

  1. 在 [IIS 管理員] 中,選取 IIS 站台之下站台節點連線資訊看板。In IIS Manager, select the IIS site under the Sites node of the Connections sidebar.
  2. 按兩下驗證IIS區域。Double-click Authentication in the IIS area.
  3. 選取 匿名驗證Select Anonymous Authentication. 選取 停用動作資訊看板。Select Disable in the Actions sidebar.
  4. 選取 Windows 驗證Select Windows Authentication. 選取 啟用動作資訊看板。Select Enable in the Actions sidebar.

IIS 管理員在採取這些動作,會修改應用程式的web.config檔案。When these actions are taken, IIS Manager modifies the app's web.config file. A<system.webServer><security><authentication>節點新增與更新的設定,如anonymousAuthenticationwindowsAuthentication:A <system.webServer><security><authentication> node is added with updated settings for anonymousAuthentication and windowsAuthentication:

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="false" />
      <windowsAuthentication enabled="true" />
    </authentication>
  </security>
</system.webServer>

<system.webServer>區段新增至web.config由 IIS 管理員中的檔案超出應用程式的<location>發佈應用程式時,由.NET Core SDK 加入的區段。The <system.webServer> section added to the web.config file by IIS Manager is outside of the app's <location> section added by the .NET Core SDK when the app is published. 因為區段會新增外部<location>節點,設定會由任何繼承子應用程式目前的應用程式。Because the section is added outside of the <location> node, the settings are inherited by any sub-apps to the current app. 若要防止繼承,移動加入<security>區段內的<location><system.webServer>SDK 所提供的一節。To prevent inheritance, move the added <security> section inside of the <location><system.webServer> section that the SDK provided.

將 IIS 設定使用 IIS 管理員時,它只會影響應用程式的web.config伺服器上的檔案。When IIS Manager is used to add the IIS configuration, it only affects the app's web.config file on the server. 後續部署應用程式可能會覆寫伺服器上的設定,如果伺服器的複本web.config專案的取代web.config檔案。A subsequent deployment of the app may overwrite the settings on the server if the server's copy of web.config is replaced by the project's web.config file. 使用任一下列其中一個方法來管理設定:Use either of the following approaches to manage the settings:

  • 使用 IIS 管理員中的設定重設web.config檔案之後部署上覆寫該檔案。Use IIS Manager to reset the settings in the web.config file after the file is overwritten on deployment.
  • 新增web.config 檔案應用程式在本機使用的設定。Add a web.config file to the app locally with the settings. 如需詳細資訊,請參閱 < 開發後端設定一節。For more information, see the Development-side configuration section.

發行,並將專案部署至 IIS 的站台資料夾Publish and deploy your project to the IIS site folder

使用 Visual Studio 或.NET Core CLI,發行應用程式並部署到目的資料夾。Using Visual Studio or the .NET Core CLI, publish and deploy the app to the destination folder.

如需有關如何使用 IIS 裝載的詳細資訊,發行和部署,請參閱下列主題:For more information on hosting with IIS, publishing, and deployment, see the following topics:

啟動應用程式以確認 Windows 驗證正常運作。Launch the app to verify Windows Authentication is working.

啟用 Windows 驗證,http.sysEnable Windows Authentication with HTTP.sys

雖然 Kestrel 不支援 Windows 驗證,您可以使用HTTP.sys支援在 Windows 上的自我裝載的案例。Although Kestrel doesn't support Windows Authentication, you can use HTTP.sys to support self-hosted scenarios on Windows. 下列範例會設定要搭配 Windows 驗證使用 HTTP.sys 的應用程式的 web 主機:The following example configures the app's web host to use HTTP.sys with Windows Authentication:

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

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .UseHttpSys(options =>
            {
                options.Authentication.Schemes = 
                    AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
                options.Authentication.AllowAnonymous = false;
            })
            .Build();
}

注意

HTTP.sys 使用 Kerberos 驗證通訊協定委派給核心模式驗證。HTTP.sys delegates to kernel mode authentication with the Kerberos authentication protocol. Kerberos 和 HTTP.sys 不支援使用者模式驗證。User mode authentication isn't supported with Kerberos and HTTP.sys. 必須使用電腦帳戶來解密 Kerberos 權杖/票證,該權杖/票證取自 Active Directory,並由用戶端將其轉送至伺服器來驗證使用者。The machine account must be used to decrypt the Kerberos token/ticket that's obtained from Active Directory and forwarded by the client to the server to authenticate the user. 請註冊主機的服務主體名稱 (SPN),而非應用程式的使用者。Register the Service Principal Name (SPN) for the host, not the user of the app.

注意

HTTP.sys 不支援 Nano Server 1709 版或更新版本上。HTTP.sys isn't supported on Nano Server version 1709 or later. 若要使用 Windows 驗證和 HTTP.sys 使用 Nano Server,請使用Server Core (microsoft/windowsservercore) 容器To use Windows Authentication and HTTP.sys with Nano Server, use a Server Core (microsoft/windowsservercore) container. 如需有關 Server Core 的詳細資訊,請參閱什麼是 Windows Server 中的 Server Core 安裝選項?For more information on Server Core, see What is the Server Core installation option in Windows Server?.

使用 Windows 驗證Work with Windows Authentication

匿名存取的設定狀態決定的方式[Authorize][AllowAnonymous]應用程式中使用屬性。The configuration state of anonymous access determines the way in which the [Authorize] and [AllowAnonymous] attributes are used in the app. 下列兩節會說明如何處理不允許和允許設定狀態的匿名存取。The following two sections explain how to handle the disallowed and allowed configuration states of anonymous access.

不允許匿名存取Disallow anonymous access

當您啟用 Windows 驗證,並已停用匿名存取,[Authorize][AllowAnonymous]屬性沒有任何作用。When Windows Authentication is enabled and anonymous access is disabled, the [Authorize] and [AllowAnonymous] attributes have no effect. 如果 IIS 網站 (或 HTTP.sys) 設定為不允許匿名存取,要求永遠不會到達您的應用程式。If the IIS site (or HTTP.sys) is configured to disallow anonymous access, the request never reaches your app. 基於這個理由,[AllowAnonymous]屬性不適用。For this reason, the [AllowAnonymous] attribute isn't applicable.

允許匿名存取Allow anonymous access

當啟用 Windows 驗證和匿名存取時,使用[Authorize][AllowAnonymous]屬性。When both Windows Authentication and anonymous access are enabled, use the [Authorize] and [AllowAnonymous] attributes. [Authorize]屬性可讓您安全的應用程式真正需要 Windows 驗證的項目。The [Authorize] attribute allows you to secure pieces of the app which truly do require Windows Authentication. [AllowAnonymous]屬性覆寫[Authorize]屬性允許匿名存取的應用程式內的使用方式。The [AllowAnonymous] attribute overrides [Authorize] attribute usage within apps which allow anonymous access. 請參閱簡單授權屬性使用方式詳細資料。See Simple Authorization for attribute usage details.

在 ASP.NET Core 2.x 中,[Authorize]屬性需要額外的設定,在Startup.cs挑戰進行 Windows 驗證的匿名要求。In ASP.NET Core 2.x, the [Authorize] attribute requires additional configuration in Startup.cs to challenge anonymous requests for Windows Authentication. 建議的設定會有些許出入所使用的 web 伺服器而有所不同。The recommended configuration varies slightly based on the web server being used.

注意

根據預設,缺少授權,才能存取頁面的使用者會看到空的 HTTP 403 回應。By default, users who lack authorization to access a page are presented with an empty HTTP 403 response. StatusCodePages 中介軟體可以設定為使用者提供更好的 「 拒絕存取 」 體驗。The StatusCodePages middleware can be configured to provide users with a better "Access Denied" experience.

IISIIS

如果使用 IIS,請將下列內容加入ConfigureServices方法:If using IIS, add the following to the ConfigureServices method:

// IISDefaults requires the following import:
// using Microsoft.AspNetCore.Server.IISIntegration;
services.AddAuthentication(IISDefaults.AuthenticationScheme);

HTTP.sysHTTP.sys

如果使用 HTTP.sys,將下列內容加入ConfigureServices方法:If using HTTP.sys, add the following to the ConfigureServices method:

// HttpSysDefaults requires the following import:
// using Microsoft.AspNetCore.Server.HttpSys;
services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);

模擬Impersonation

ASP.NET Core 不會實作模擬。ASP.NET Core doesn't implement impersonation. 應用程式執行的所有要求,使用應用程式集區或處理序身分識別的應用程式的身分識別。Apps run with the app's identity for all requests, using app pool or process identity. 如果您需要明確地執行動作的使用者身分,使用WindowsIdentity.RunImpersonated終端機內嵌中介軟體Startup.ConfigureIf you need to explicitly perform an action on behalf of a user, use WindowsIdentity.RunImpersonated in a terminal inline middleware in Startup.Configure. 在此內容中執行單一動作,然後關閉 內容。Run a single action in this context and then close the context.

app.Run(async (context) =>
{
    try
    {
        var user = (WindowsIdentity)context.User.Identity;

        await context.Response
            .WriteAsync($"User: {user.Name}\tState: {user.ImpersonationLevel}\n");

        WindowsIdentity.RunImpersonated(user.AccessToken, () =>
        {
            var impersonatedUser = WindowsIdentity.GetCurrent();
            var message =
                $"User: {impersonatedUser.Name}\t" +
                $"State: {impersonatedUser.ImpersonationLevel}";

            var bytes = Encoding.UTF8.GetBytes(message);
            context.Response.Body.Write(bytes, 0, bytes.Length);
        });
    }
    catch (Exception e)
    {
        await context.Response.WriteAsync(e.ToString());
    }
});

RunImpersonated 不支援非同步作業,而不應該用於複雜的案例。RunImpersonated doesn't support asynchronous operations and shouldn't be used for complex scenarios. 比方說,包裝整個要求或中介軟體鏈結不支援或建議。For example, wrapping entire requests or middleware chains isn't supported or recommended.

宣告轉換Claims transformations

當 IIS 同處理序模式中,裝載AuthenticateAsync不在內部呼叫以初始化使用者。When hosting with IIS in-process mode, AuthenticateAsync isn't called internally to initialize a user. 因此,預設會在未啟動每個驗證之後,使用 IClaimsTransformation 實作來轉換宣告。Therefore, an IClaimsTransformation implementation used to transform claims after every authentication isn't activated by default. 如需裝載同處理序時,會啟用宣告轉換的程式碼範例和詳細資訊,請參閱ASP.NET Core 模組For more information and a code example that activates claims transformations when hosting in-process, see ASP.NET Core 模組.