1

I want to add some policies to ASP.Net Core authorization, which are stored in my database (EF Core with MySQL). The goal is to limit users' access based on their authorities. As far as I know, I should do it in the ConfigureServices method in the Startup class like this:

services.AddAuthorizationCore(options =>
{
  options.AddPolicy("CanEditUserGroups", builder =>
  {
    builder.RequireAuthenticatedUser();
    builder.RequireClaim("Permission", "Value");
  });
});

But, the problem is that I want to have several policies and read their "Value" from the database. Is it possible to instantiate my DbContext service and read data from that? Am I doing it the right way?

Amir Fakhim Babaei
  • 481
  • 1
  • 3
  • 12

1 Answers1

2

I found the solution. For those who might face this problem in the future, here is one way to do that:

var serviceProvider = services.BuildServiceProvider();
var permissionRepository =
    (IPermissionRepository)serviceProvider.GetService<IPermissionRepository>();
var permissions = permissionRepository.GetAll();

services.AddAuthorizationCore(options =>
{
    foreach (var permission in permissions)
    {
        options.AddPolicy("permission.Title", builder =>
        {
            builder.RequireAuthenticatedUser();
            builder.RequireClaim("Permission", permission.Title);
        });
    }
});
Amir Fakhim Babaei
  • 481
  • 1
  • 3
  • 12
  • warning: BuildServiceProvider() results in additional copies of all Singleton services being created. Check for full explaination:https://stackoverflow.com/questions/56042989/what-are-the-costs-and-possible-side-effects-of-calling-buildserviceprovider-i – Micheal Choudhary Oct 31 '20 at 02:43