Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 617
gezzahead Avatar asked Sep 07 '25 20:09

gezzahead


1 Answers

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

like image 177
Rufus Lobo Avatar answered Sep 09 '25 09:09

Rufus Lobo