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

Microsoft Blazor inject Controller Base HTTP Context for accessing User Authentication

I have a Microsoft Blazor application which is using Custom Authentication provider to authenticate users by matching them with the database record and expose the necessary cookies. This provider adds also the necessary claims into HttpContext like the following:

var claims = new List<Claim>
{
    new Claim(ClaimTypes.Sid, auth_id.ToString()), //TAKE USER ID FROM VALID USER FROM DATABASE AFTER VALIDATION
    new Claim(ClaimTypes.Name, authentication.user_name.ToString()),
};
var claimsIdentity = new ClaimsIdentity(claims, "Authentication");

var properties = new AuthenticationProperties()
{
    IsPersistent = true,
    AllowRefresh = true
};

HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), properties);

Now I need to be able to access this HttpContext (of ControllerBase) into Services as I need to pass the user_id into a DataSecurityFilter function I have which filters data based on user_id.

For injecting the DBContext, I use the following code though constructor:

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

public class Service_Auth : Interface_Auth
{
    readonly DatabaseContext_Management _dbContext = new();

    public Service_Auth(DatabaseContext_Management dbContext, HttpContext httpContext)
    {
        _dbContext = dbContext;
    }
}

My intention is to get the user_id like this:

ClaimsPrincipal claimsPrincipal = httpContext.User;
string? user_sid = claimsPrincipal.Claims.Where(x => x.Type == ClaimTypes.Sid).Select(x => x.Value).FirstOrDefault();
if (user_sid != null)
{ user_id = Convert.ToInt32(user_sid); }

But how can I inject the HTTPContext of ControllerBase?

>Solution :

In Program.cs add:

builder.Services.AddHttpContextAccessor();
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