Search code examples
asp.net-coreentity-framework-coreasp.net-authorization

Access database (EF Core DbContext) in ConfigureServices of ASP.Net Core


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?


Solution

  • 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);
            });
        }
    });