0

I'm trying to implement a roles / permissions system in my application, but I can't figure how to use DbContext inside m AuthorizeAttributeClass.

Here is the code that I am using :

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using HygeneApi.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace HygeneApi.Authorization

{


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class PrivilegeAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
    private readonly string _privilege;
    private readonly ConcreetDataContext _context;


    public PrivilegeAuthorizeAttribute(string privilege)
    {
        _privilege = privilege;
    }

    public async void OnAuthorization(AuthorizationFilterContext context)
    {
        var user = context.HttpContext.User;
        IServiceCollection serviceCollection = new ServiceCollection();

        using (var contexte = new ConcreetDataContext(serviceCollection.GetService<DbContextOptions<ConcreetDataContext>>()))
        {
            var currentUser = await _context.Users.AsQueryable().FirstOrDefaultAsync(u => u.Email == user.Identity.Name);
            Console.WriteLine(currentUser.FirstName);
        }

    }
}

I'm getting the error : "IServiceCollection does not contain a definition for GetService .... "

And I can't also use Microsoft.Extensions.DependencyInjection.Abstractions :

I've installed the package and everything, but I'm always having the type or namespace name Abstractions does not exist in Microsoft.Extensions.DependencyInjection.

Thank you in advance for your help !

Mohammed Chanaa
  • 93
  • 2
  • 10
  • Hi. You need to use the same ServiceCollection instance of your startup class. You can make a public static field in your startup class to expose the ServiceProvider. I'm curious if you find better solution – Bisjob Jun 24 '21 at 09:26
  • @Bisjob I've thought of that in advance, but I don't think that it's the best solution here. – Mohammed Chanaa Jun 24 '21 at 09:29
  • Possible duplicate: https://stackoverflow.com/questions/29915192/dependency-injection-in-attributes – Steven Jun 24 '21 at 09:38
  • 1
    This appears to be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). However as mentioned in a previous comment it is usually advised against using dependency injection in attributes. Service locator can be used by accessing the service provider of the current request through the HttpContext to resolve the required dependency but that is also seen as a code smell. Review your current design as there a multiple issues with your approach. – Nkosi Jun 24 '21 at 13:27
  • @Nkosi Thank you, can you please advise me further on how to implement in the correct way authorization on my application, using Roles and Privileges for users. – Mohammed Chanaa Jun 25 '21 at 11:13

0 Answers0