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:
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?
In Program.cs add:
builder.Services.AddHttpContextAccessor();
An Example usage:
public TenantService(
IBlobBroker blobBroker,
IHttpContextAccessor httpContextAccessor,
IDateTimeBroker dateTimeBroker,
IGuidBroker guidBroker,
ILoggingBroker loggingBroker,
LocalConfiguration localConfiguration)
{
if (blobBroker is null)
{
var blobBrokerNullException =
new ArgumentNullException(nameof(blobBroker));
throw new TenantDependencyAggregateException(blobBrokerNullException);
}
this.blobBroker = blobBroker;
this.httpContextAccessor = httpContextAccessor;
this.dateTimeBroker = dateTimeBroker;
this.guidBroker = guidBroker;
this.loggingBroker = loggingBroker;
this.localConfiguration = localConfiguration;
}