Search code examples
asp.net-mvc-5asp.net-core-mvc

.NET Core MVC 5 Windows Authentication


I want to use Windows Authentication on my .NET Core MVC 5 web app. To allow specific domain users and an AD group.

I added a web.config in the root:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.web>
    <authentication mode="Windows" />
    <authorization>
      <allow users="mydomain\username1, mydomain\username2" />
      <deny users="?" />
    </authorization>
    <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
      <providers>
        <clear />
        <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
      </providers>
    </roleManager>
  </system.web>
</configuration>

I added this to startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
        }

I added this in my controller

[Authorize(Roles = @"mydomain\ADgroupName")]
[Authorize(Users = @"mydomain\username1")]
public class HomeController : Controller

In project properties I disabled Anonymous auth and enabled Windows auth.

I added a project reference to Microsoft.AspNetCore.Authentication.

When all that is said and done I get the error "Type or namespace 'Users' could not be found".

What am I missing here?


Solution

  • the error "Type or namespace 'Users' could not be found".

    From the AuthorizeAttribute Class, we can see that the Authorize attribute only have the Roles and Policy property, without the Users property, so it will show the above error.

    If you want to set authorization rights for specified users, you could create a policy for the users, then, in the Controller, set the Authorize attribute as below:

     [Authorize(Policy = "policyforUser")]
     public class HomeController : Controller
    

    More detail information about create policy, see the following links:

    Policy-based authorization in ASP.NET Core

    ASP.NET Core Authorize AD Groups through web.config

    ASP.NET Core - Authorization Using Windows Authentication

    Using AD groups to authorise access to pages using IIS Windows Authentication