在 ASP.NET Core 中配置 Windows 身份验证Configure Windows Authentication in ASP.NET Core

通过Scott AddieLuke LathamBy Scott Addie and Luke Latham

Windows 身份验证 (也称为协商、 Kerberos 或 NTLM 的身份验证) 可以配置为使用托管的 ASP.NET Core 应用IISKestrel,或HTTP.sys.Windows Authentication (also known as Negotiate, Kerberos, or NTLM authentication) can be configured for ASP.NET Core apps hosted with IIS, Kestrel, or HTTP.sys.

Windows 身份验证 (也称为协商、 Kerberos 或 NTLM 的身份验证) 可以配置为使用托管的 ASP.NET Core 应用IISHTTP.sysWindows Authentication (also known as Negotiate, Kerberos, or NTLM 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 域的 intranet 环境。Windows Authentication is best suited to intranet environments where users, client apps, and web servers belong to the same Windows domain.

备注

使用 HTTP/2 不支持 Windows 身份验证。Windows Authentication isn't supported with HTTP/2. 可以在 HTTP/2 响应发送身份验证质询,但客户端必须降级到 HTTP/1.1 之前进行身份验证。Authentication challenges can be sent on HTTP/2 responses, but the client must downgrade to HTTP/1.1 before authenticating.

IIS/IIS ExpressIIS/IIS Express

添加身份验证服务通过调用AddAuthentication(Microsoft.AspNetCore.Server.IISIntegration命名空间) 中Startup.ConfigureServices:Add authentication services by invoking AddAuthentication (Microsoft.AspNetCore.Server.IISIntegration namespace) in Startup.ConfigureServices:

services.AddAuthentication(IISDefaults.AuthenticationScheme);

启动设置 (调试器)Launch settings (debugger)

用于配置启动设置,只会影响Properties/launchSettings.json IIS express 文件,并不会配置 IIS 的 Windows 身份验证。Configuration for launch settings only affects the Properties/launchSettings.json file for IIS Express and doesn't configure IIS for Windows Authentication. 服务器配置中所述IIS部分。Server configuration is explained in the IIS section.

Web 应用程序可通过 Visual Studio 或.NET Core CLI 的模板可以配置为支持 Windows 身份验证,这会更新Properties/launchSettings.json文件是自动的。The Web Application template available via Visual Studio or the .NET Core CLI can be configured to support Windows Authentication, which updates the Properties/launchSettings.json file automatically.

新项目New project

  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.

现有项目Existing project

项目的属性启用 Windows 身份验证并禁用匿名身份验证:The project's properties enable Windows Authentication and disable Anonymous Authentication:

  1. 右键单击“解决方案资源管理器”中的项目,再选择“属性” 。Right-click the project in 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.
  5. 保存并关闭属性页。Save and close the property page.

或者,可以在配置属性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": 44308
    }
}

在修改现有项目,确认项目文件包含的包引用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.

IISIIS

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 能够承载 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 集成中间件默认配置为自动进行身份验证请求。IIS Integration Middleware is configured to automatically authenticate requests by default. 有关详细信息,请参阅与 IIS 的 Windows 上托管 ASP.NET Core: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.

使用任一以下方法之一:Use either of the following approaches:

  • 发布和部署该项目之前, 添加以下web.config到项目根目录的文件:Before publishing and deploying the project, 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>
    

    由.NET Core SDK 发布项目时 (而无需<IsTransformWebConfigDisabled>属性设置为true项目文件中),已发布web.config文件包括<location><system.webServer><security><authentication>部分。When the project is published by the .NET Core 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 管理器:After publishing and deploying the project, perform server-side configuration with the IIS Manager:

    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. 一个<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>.NET Core SDK 提供的部分。To prevent inheritance, move the added <security> section inside of the <location><system.webServer> section that the .NET Core 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.

KestrelKestrel

Microsoft.AspNetCore.Authentication.Negotiate NuGet 包可用于Kestrel以支持 Windows、 Linux 和 macOS 上使用 Negotiate、 Kerberos 和 NTLM 的 Windows 身份验证。The Microsoft.AspNetCore.Authentication.Negotiate NuGet package can be used with Kestrel to support Windows Authentication using Negotiate, Kerberos, and NTLM on Windows, Linux, and macOS.

警告

凭据可以在连接上的请求之间得以保持。Credentials can be persisted across requests on a connection. 协商身份验证不得使用代理中使用,除非代理维护与 Kestrel 1 对 1 连接关联 (持续性连接)。Negotiate authentication must not be used with proxies unless the proxy maintains a 1:1 connection affinity (a persistent connection) with Kestrel.

备注

Negotiate 处理程序会检测基础服务器以本机方式支持 Windows 身份验证,并启用它。The Negotiate handler detects if the underlying server supports Windows Authentication natively and if it's enabled. 如果服务器支持 Windows 身份验证,但它处于禁用状态,要求你启用服务器实现引发错误。If the server supports Windows Authentication but it's disabled, an error is thrown asking you to enable the server implementation. 当服务器中启用 Windows 身份验证时,Negotiate 处理程序以透明方式将转发给它。When Windows Authentication is enabled in the server, the Negotiate handler transparently forwards to it.

添加身份验证服务通过调用AddAuthentication(Microsoft.AspNetCore.Authentication.Negotiate命名空间) 和AddNegotitate(Microsoft.AspNetCore.Authentication.Negotiate命名空间) 中Startup.ConfigureServices:Add authentication services by invoking AddAuthentication (Microsoft.AspNetCore.Authentication.Negotiate namespace) and AddNegotitate (Microsoft.AspNetCore.Authentication.Negotiate namespace) in Startup.ConfigureServices:

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

通过调用添加身份验证中间件UseAuthenticationStartup.Configure:Add Authentication Middleware by calling UseAuthentication in Startup.Configure:

app.UseAuthentication();

app.UseMvc();

中间件的详细信息,请参阅ASP.NET Core 中间件For more information on middleware, see ASP.NET Core 中间件.

允许匿名请求。Anonymous requests are allowed. 使用ASP.NET Core 授权质询的身份验证的匿名请求。Use ASP.NET Core Authorization to challenge anonymous requests for authentication.

Windows 环境配置Windows environment configuration

Microsoft.AspNetCore.Authentication.Negotiate组件执行用户模式身份验证。The Microsoft.AspNetCore.Authentication.Negotiate component performs User Mode authentication. 服务主体名称 (Spn) 必须添加到运行服务,而不是计算机帐户的用户帐户。Service Principal Names (SPNs) must be added to the user account running the service, not the machine account. 执行setspn -S HTTP/mysrevername.mydomain.com myuser管理命令行界面中。Execute setspn -S HTTP/mysrevername.mydomain.com myuser in an administrative command shell.

Linux 和 macOS 的环境配置Linux and macOS environment configuration

中提供了有关在 Linux 或 macOS 计算机加入 Windows 域的说明Azure 数据 Studio 连接到 SQL Server 使用 Windows 身份验证的 Kerberos一文。Instructions for joining a Linux or macOS machine to a Windows domain are available in the Connect Azure Data Studio to your SQL Server using Windows authentication - Kerberos article. 说明在域中创建的 Linux 计算机的计算机帐户。The instructions create a machine account for the Linux machine on the domain. 必须将 Spn 添加到该计算机帐户。SPNs must be added to that machine account.

备注

时中的指南Azure 数据 Studio 连接到 SQL Server 使用 Windows 身份验证的 Kerberos文章中,替换python-software-propertiespython3-software-properties必要。When following the guidance in the Connect Azure Data Studio to your SQL Server using Windows authentication - Kerberos article, replace python-software-properties with python3-software-properties if needed.

一旦在 Linux 或 macOS 计算机加入到域,需要提供额外的步骤keytab 文件的 spn:Once the Linux or macOS machine is joined to the domain, additional steps are required to provide a keytab file with the SPNs:

  • 在域控制器上,将添加到的计算机帐户的新的 web 服务的 Spn:On the domain controller, add new web service SPNs to the machine account:
    • setspn -S HTTP/mywebservice.mydomain.com mymachine
    • setspn -S HTTP/mywebservice@MYDOMAIN.COM mymachine
  • 使用ktpass生成 keytab 文件:Use ktpass to generate a keytab file:
    • ktpass -princ HTTP/mywebservice.mydomain.com@MYDOMAIN.COM -pass myKeyTabFilePassword -mapuser MYDOMAIN\mymachine$ -pType KRB5_NT_PRINCIPAL -out c:\temp\mymachine.HTTP.keytab -crypto AES256-SHA1
    • 某些字段必须以指定大写所示。Some fields must be specified in uppercase as indicated.
  • 将 keytab 文件复制到 Linux 或 macOS 计算机。Copy the keytab file to the Linux or macOS machine.
  • 选择通过环境变量的 keytab 文件: export KRB5_KTNAME=/tmp/mymachine.HTTP.keytabSelect the keytab file via an environment variable: export KRB5_KTNAME=/tmp/mymachine.HTTP.keytab
  • 调用klist以显示当前可供使用的 Spn。Invoke klist to show the SPNs currently available for use.

备注

Keytab 文件包含域访问凭据,必须相应地保护。A keytab file contains domain access credentials and must be protected accordingly.

HTTP.sysHTTP.sys

HTTP.sys支持内核模式 Windows 身份验证使用 Negotiate、 NTLM 或基本身份验证。HTTP.sys supports Kernel Mode Windows Authentication using Negotiate, NTLM, or Basic authentication.

添加身份验证服务通过调用AddAuthentication(Microsoft.AspNetCore.Server.HttpSys命名空间) 中Startup.ConfigureServices:Add authentication services by invoking AddAuthentication (Microsoft.AspNetCore.Server.HttpSys namespace) in Startup.ConfigureServices:

services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);

配置应用程序的 web 主机,以使用 Windows 身份验证使用 HTTP.sys (Program.cs)。Configure the app's web host to use HTTP.sys with Windows Authentication (Program.cs). UseHttpSysMicrosoft.AspNetCore.Server.HttpSys命名空间。UseHttpSys is in the Microsoft.AspNetCore.Server.HttpSys namespace.

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

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>()
                    .UseHttpSys(options =>
                    {
                        options.Authentication.Schemes = 
                            AuthenticationSchemes.NTLM | 
                            AuthenticationSchemes.Negotiate;
                        options.Authentication.AllowAnonymous = false;
                    });
            });
}
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. 必须使用计算机帐户来解密从 Active Directory 获取的并由客户端转发到服务器的 Kerberos 令牌/票证,以便对用户进行身份验证。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 中的服务器核心安装选项?For more information on Server Core, see What is the Server Core installation option in Windows Server?.

为用户授权Authorize users

匿名访问的配置状态确定的方式[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 站点配置为不允许匿名访问,请求将永远不会到达该应用程序。If an IIS site is configured to disallow anonymous access, the request never reaches the 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]特性,您可以保护的应用程序的要求进行身份验证的终结点。The [Authorize] attribute allows you to secure endpoints of the app which require authentication. [AllowAnonymous]特性重写[Authorize]允许匿名访问的应用中的属性。The [AllowAnonymous] attribute overrides the [Authorize] attribute in apps that allow anonymous access. 属性使用情况详细信息,请参阅ASP.NET Core 中的简单授权For attribute usage details, see ASP.NET Core 中的简单授权.

备注

默认情况下,缺少授权可访问的页面的用户会显示 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.

ImpersonationImpersonation

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 the app should 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.

虽然Microsoft.AspNetCore.Authentication.Negotiate程序包可启用 Windows 上的身份验证,在 Windows 上仅支持 Linux 和 macOS 的模拟。While the Microsoft.AspNetCore.Authentication.Negotiate package enables authentication on Windows, Linux, and macOS, impersonation is only supported on Windows.

声明转换Claims transformations

使用 IIS,承载时AuthenticateAsync不在内部调用以初始化用户。When hosting with IIS, 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, see ASP.NET Core 模块.

承载与 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 模块.

其他资源Additional resources