Search code examples
c#asp.netasp.net-identity

ASP.NET core authorize role with AD group from appsettings


It seems like it should be really easy, as on my controller this works:

[Authorize(Roles = "domain\\ad_group")]
public class MyController : Controller

However I would like to specify the "domain\ad_group" from appsettings, rather than hard-coded. I realize the 'proper' solution is to use eg. the EF roles/policies etc, however this is a very tiny application so I'm looking for something a bit more lightweight.

Can I get the AD group from appsettings in a simple way?


Solution

  • Try the attribute: [Authorize(Policy = "MyPolicyName")]

    In the ConfigureServices method perform the following 2 steps:
    1. Read the required role (AD Group) from the appsettings.json file.
    2. Add that role to this policy using the RequireRole method.

    Code for Step 1:

    Configuration.GetSection("NameOfSectionInAppSettings").Bind(ObjectTheSectionIsMappedTo);
    

    Code for Step 2:

    services.AddAuthorization(options =>
    { options.AddPolicy("MyPolicyName", policy => policy.RequireRole(ObjectTheSectionIsMappedTo.AdGroupProperty)); });
    

    This works for one of the tiny applications I developed :)