.net-corec#-4.0dependency-injectionauthorize-attribute

.Net Core Dependency Injection without passing Dependency in Constructor


I am implementing custom [Authorize] attribute. Inside the OnAuthorization method in IdentityAuthorizeFilter Class, I need to have access to DBContext to perform Database checks. I can not pass the context in the constructor of the Class. How can I access DBContext inside this class ?

Startup.cs

public void ConfigureServices(IServiceCollection services)
{            
            services.AddDbContext<SecureContext>(options =>
                  options.UseSqlServer(Configuration.GetConnectionString("SecureContext")));
}

CustomAuthorize:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class IdentityAuthorizeAttribute : TypeFilterAttribute
{
    public IdentityAuthorizeAttribute(string permissions)
        : base(typeof(IdentityAuthorizeFilter))
    {
        Arguments = new object[] { permissions };
    }
}

public class IdentityAuthorizeFilter : IAuthorizationFilter
{

    public IdentityAuthorizeFilter(string permissions) => Permissions = permissions;
    public string Permissions { get; set; }


    [Authorize]
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var claims = context.HttpContext.User.Claims.ToList();
        var auth = context.HttpContext.User.Identity.IsAuthenticated;

        //Access DB Context
        
        if (!isAuthorized)
            context.Result = new UnauthorizedResult();
    }
}

Solution

  • Does this work?

    var dbContext = context.HttpContext.RequestServices.GetRequiredService<SecureContext>();
    

    I'm not sure if it will, but I did something similar using Microsoft's AddMicrosoftIdentityWebApp method like this:

    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
            .AddMicrosoftIdentityWebApp(
            options =>
            {
                configuration.Bind("AzureAD", options);
                options.Events ??= new OpenIdConnectEvents();
                options.Events.OnTokenValidated += async tokenValidatedContext =>
                {
                    var dbContext = tokenValidatedContext.HttpContext.RequestServices.GetRequiredService<dbContext>();
                    // Do stuff with db context here
                };
            });