Windows Authentication in .net Core 2.1 application

LanceM

I've got a .net Core 2.1 MVC application that hosts an Angular 6 application. I am using Visual Studio 2017 15.7.3. I'm trying to set up Windows Authentication but am having issues. I've followed the documentation and my Program.cs and Startup.cs are below:

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

If I uncomment the .UseHttpSys section in program.cs and press play in Visual Studio to debug, it almost immediately stops the debug session and the following error is in the Event log:

"Application 'MACHINE/WEBROOT/APPHOST/myapp' with physical root 'C:\Users\me\myapp' created process with commandline '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"' but failed to listen on the given port '28353'".

If I try with .UseHttpSys commented out, the debugging works but I am unable to be properly authenticated.

LanceM

Camilo thanks for your comment, it helped point me in the right direction. I removed the UseHttpSys section from program.cs and added .UseIISIntegration(). I also changed services.AddAuthentication(HttpSysDefaults.AuthenticationScheme) to services.AddAuthentication(IISDefaults.AuthenticationScheme) in my startup.cs. I then ticked Enable Windows Authentication in the Debug section of the project properties and chose "IIS Express" for the Launch and it all worked. I'm new to .net core with windows authentication so I don't know if I got it all set up exactly correct but it works and hopefully, this post helps point others in the right direction.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Windows Authentication with asp.net core

分類Dev

JWT Authentication for .net core 2.2 application not using Identity

分類Dev

Use ADFS-based authentication inside ASP.NET Core to access a SQL Server using Windows authentication?

分類Dev

Application Insights in Net Core 2 WebApi - Share Context To Append Properties

分類Dev

Windows Authentication doesn't work in Microsoft Edge browser for Angular 2 application

分類Dev

ASP.Net Core SAML authentication

分類Dev

ASP.Net Core SAML authentication

分類Dev

ASP.Net Core SAML authentication

分類Dev

ASP.NET Core 2.0 authentication middleware

分類Dev

Can't add ref to windows store application since it targets .NET Core

分類Dev

Change authentication from no authentication to individual authentication in existing project of Asp.Net Core (MVC)

分類Dev

Where can I find the ASP.NET Core 2 source code? Specifically for Microsoft.AspNetCore.Authentication.OpenIdConnect

分類Dev

Azure WebApp Asp.NET Core 2 error: An error occurred while starting the application

分類Dev

How to host the basic ASP.NET Core 2 WebAPI application on IIS

分類Dev

JWT authentication in SignalR (.NET Core) without passing token in Query String

分類Dev

Custom Authentication using legacy user table in Asp.Net Core

分類Dev

Path based authentication in ASP.NET Core MVC 2.0

分類Dev

Custom Role with .NET Core 3 Azure AD Authentication

分類Dev

ASP.Net Core SignalR authentication always responding with 403 - Forbidden

分類Dev

Path to LocalAppData in ASP.Net Core application

分類Dev

Localizable asp.net core + reactjs application

分類Dev

Debug .net core application deployed on local IIS?

分類Dev

#nginxhelp Reverse Proxy to Microsoft IIS Server with Windows Authentication on the Application

分類Dev

.NET Core X509Certificate2の使用法(Windows / IIS、Docker、Linuxで)

分類Dev

Asp.Net Core 2 Web API shows HTTP 404 error on Visual Studio 2017, Windows 10

分類Dev

.NET Core 2 Password Hashing

分類Dev

.NET Core EF Core2モデルを1つのビューで作成操作

分類Dev

Turn off / Disable windows authentication for asp.net-mvc

分類Dev

Using .NET Core library in .NET 4.5.2 console application

Related 関連記事

  1. 1

    Windows Authentication with asp.net core

  2. 2

    JWT Authentication for .net core 2.2 application not using Identity

  3. 3

    Use ADFS-based authentication inside ASP.NET Core to access a SQL Server using Windows authentication?

  4. 4

    Application Insights in Net Core 2 WebApi - Share Context To Append Properties

  5. 5

    Windows Authentication doesn't work in Microsoft Edge browser for Angular 2 application

  6. 6

    ASP.Net Core SAML authentication

  7. 7

    ASP.Net Core SAML authentication

  8. 8

    ASP.Net Core SAML authentication

  9. 9

    ASP.NET Core 2.0 authentication middleware

  10. 10

    Can't add ref to windows store application since it targets .NET Core

  11. 11

    Change authentication from no authentication to individual authentication in existing project of Asp.Net Core (MVC)

  12. 12

    Where can I find the ASP.NET Core 2 source code? Specifically for Microsoft.AspNetCore.Authentication.OpenIdConnect

  13. 13

    Azure WebApp Asp.NET Core 2 error: An error occurred while starting the application

  14. 14

    How to host the basic ASP.NET Core 2 WebAPI application on IIS

  15. 15

    JWT authentication in SignalR (.NET Core) without passing token in Query String

  16. 16

    Custom Authentication using legacy user table in Asp.Net Core

  17. 17

    Path based authentication in ASP.NET Core MVC 2.0

  18. 18

    Custom Role with .NET Core 3 Azure AD Authentication

  19. 19

    ASP.Net Core SignalR authentication always responding with 403 - Forbidden

  20. 20

    Path to LocalAppData in ASP.Net Core application

  21. 21

    Localizable asp.net core + reactjs application

  22. 22

    Debug .net core application deployed on local IIS?

  23. 23

    #nginxhelp Reverse Proxy to Microsoft IIS Server with Windows Authentication on the Application

  24. 24

    .NET Core X509Certificate2の使用法(Windows / IIS、Docker、Linuxで)

  25. 25

    Asp.Net Core 2 Web API shows HTTP 404 error on Visual Studio 2017, Windows 10

  26. 26

    .NET Core 2 Password Hashing

  27. 27

    .NET Core EF Core2モデルを1つのビューで作成操作

  28. 28

    Turn off / Disable windows authentication for asp.net-mvc

  29. 29

    Using .NET Core library in .NET 4.5.2 console application

ホットタグ

アーカイブ