Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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
            };
        });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading