gezzahead
gezzahead

Reputation: 1266

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?

Upvotes: 4

Views: 4048

Answers (1)

Rufus Lobo
Rufus Lobo

Reputation: 375

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 :)

Upvotes: 10

Related Questions