首页 > 解决方案 > .net Core 2.1 应用程序中的 Windows 身份验证

问题描述

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

程序.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
}
}

启动.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"
                });
        });
    }
 }
}

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

“具有物理根目录 'C:\Users\me\myapp' 的应用程序 'MACHINE/WEBROOT/APPHOST/myapp' 使用命令行 'C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\ Extensions\Microsoft\Web Tools\ProjectSystem\VSIISExeLauncher.exe -argFile "C:\Users\me\AppData\Local\Temp\tmpFCA6.tmp"' 但未能侦听给定端口 '28353'"。

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

标签: c#asp.net-corewindows-authentication

解决方案


卡米洛感谢您的评论,它帮助我指明了正确的方向。我从 program.cs 中删除了 UseHttpSys 部分并添加了.UseIISIntegration(). 我也改成services.AddAuthentication(HttpSysDefaults.AuthenticationScheme)services.AddAuthentication(IISDefaults.AuthenticationScheme)我的startup.cs. 然后我在项目属性的调试部分打勾Enable Windows Authentication,并为启动选择“IIS Express”,一切正常。我是 Windows 身份验证的 .net 核心新手,所以我不知道我的设置是否完全正确,但它可以工作,希望这篇文章有助于为其他人指明正确的方向。


推荐阅读