.NET Core 2.1 Windows 身份验证无法识别角色成员资格

.NET Core 2.1 Windows authentication does not recognise role membership

我已经按照我能找到的教程和 Stack Overflow 问题进行操作,但仍然有一个问题,我在使用 [Authorize] 属性装饰的方法上收到 403 Forbidden。

这是一种有效的方法,可以证明 Google Chrome 在调试期间将我的 Windows 凭据传递到 IISExpress 中 运行 的站点。

public IActionResult Index()
        {
            ViewBag.UserIdentityIsAuthenticated = User.Identity.IsAuthenticated;
            ViewBag.UserIdentityName = User.Identity.Name;
            ViewBag.UserIsInRoleTechnical = User.IsInRole("ADSecurityGroupOne");
            ViewBag.UserIsInRoleTechnicalPeople = User.IsInRole("ADSecurityGroupOneTwo");

            return View();
        }

此方法失败并返回 403,它只应显示视图,尚未链接到任何数据库。

    [Authorize(Policy = "AllowedOnly")]
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Index(AccountViewModel model)
    {
        if (ModelState.IsValid)
        {
            return View();
        }
        else
            return View();
    }

这是 Startup.cs

中的 ConfigureServices 方法
public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddOptions();
            ApplicationSettings appSettings = new ApplicationSettings();
            Configuration.GetSection("ApplicationSettings").Bind(appSettings);
            
            services.AddAuthentication(IISDefaults.AuthenticationScheme);
            services.AddAuthorization(options => options.AddPolicy("AllowedOnly", policy => policy.RequireRole(appSettings.AllowedToMigrate)));
        }

我已确认 AllowedToMigrate 的值与 appsettings.json 中指定的值相同。

{
  "ApplicationSettings": {
    "AllowedToMigrate": "ADSecurityGroupOne,ADSecurityGroupTwo"
  },

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

为什么 [Authorize(Policy = "AllowedOnly"] 失败了?

我认为您需要将 AllowedToMigrate 值拆分为组件角色,而不是将其作为一个字符串提交。

你真正想要实现的是

services.AddAuthorization(options => options.AddPolicy("AllowedOnly", 
    policy => policy.RequireRole("ADSecurityGroupOne", "ADSecurityGroupTwo")));

我不完全确定您将如何从单个配置设置中做到这一点 - 可能是通过创建新要求:

https://docs.microsoft.com/en-us/aspnet/core/security/authorization/policies?view=aspnetcore-2.1

回答我自己的问题,因为我弄清楚我做错了什么:

如果有多个角色,则必须以字符串数组的形式提供角色;如果只有一个,则只能提供一个字符串。我更新了 json 应用程序设置文件和我的 ApplicationSettings class,以便 AllowedToMigrate 是一个字符串数组。

{
  "ApplicationSettings": {
    "AllowedToMigrate": [ "ADSecurityGroupOne", "ADSecurityGroupTwo" ]
  },

  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

我还修复了原问题的角色名称拼写错误!所以这个故事的寓意是:绝对确保您使用的是正确拼写的角色名称,并且在授权似乎无缘无故地出错时始终尝试使用不同的角色。