Windows .net Core 2.1 应用程序中的身份验证

Windows Authentication in .net Core 2.1 application

我有一个托管 Angular 6 应用程序的 .net Core 2.1 MVC 应用程序。我正在使用 Visual Studio 2017 15.7.3。我正在尝试设置 Windows 身份验证,但遇到问题。我已经按照文档进行操作,我的 Program.cs 和 Startup.cs 如下:

Program.cs:

using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;

namespace CoreIV_Admin_Core
{
public class Program
{
    public static void Main(string[] args)
    {
        var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

        try
        {
            logger.Debug("init main");
            CreateWebHostBuilder(args).Build().Run();
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of exception");
            throw;
        }
        finally
        {
            // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
            NLog.LogManager.Shutdown();
        }
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            //.UseHttpSys(options =>
            //{
            //    options.Authentication.Schemes = AuthenticationSchemes.NTLM | AuthenticationSchemes.Negotiate;
            //    options.Authentication.AllowAnonymous = false;
            //})
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Information);
            })
            .UseNLog(); // NLog: setup NLog for Dependency injection
}
}

Startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace CoreIV_Admin_Core
{
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration
    {
        get;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        services.AddAuthentication(HttpSysDefaults.AuthenticationScheme);

        services.AddMvc()
               .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
            {
                HotModuleReplacement = true
            });
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseCookiePolicy();

        app.UseHttpContext();

        app.UseAuthentication();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            routes.MapSpaFallbackRoute(
                name: "spa-fallback",
                defaults: new
                {
                    controller = "Home",
                    action = "Index"
                });
        });
    }
 }
}

如果我在 program.cs 中取消注释 .UseHttpSys 部分并在 Visual Studio 中按播放键进行调试,它几乎会立即停止调试会话,并且事件日志中会出现以下错误:

"Application 'MACHINE/WEBROOT/APPHOST/myapp' with physical root 'C:\Users\me\myapp' created process with commandline 'C:\Program Files (x86)\Microsoft Visual Studio17\Professional\Common7\IDE\Extensions\Microsoft\Web Tools\ProjectSystem\VSIISExeLauncher.exe -argFile "C:\Users\me\AppData\Local\Temp\tmpFCA6.tmp"' but failed to listen on the given port '28353'".

如果我尝试将 .UseHttpSys 注释掉,调试工作正常但我无法正确验证。

Camilo 感谢您的评论,它帮助我指明了正确的方向。我从 program.cs 中删除了 UseHttpSys 部分并添加了 .UseIISIntegration()。我还在 startup.cs 中将 services.AddAuthentication(HttpSysDefaults.AuthenticationScheme) 更改为 services.AddAuthentication(IISDefaults.AuthenticationScheme)。然后我在项目属性的调试部分勾选 Enable Windows Authentication 并为启动选择 "IIS Express" 并且一切正常。我是使用 windows 身份验证的 .net 核心的新手,所以我不知道我是否完全正确地设置了它,但它确实有效,希望这个 post 可以帮助其他人指明正确的方向。