The helper class and interface for getting information about an authorized user. Included in the general set of auxiliary libraries: Alva.ServiceKit.*
$ dotnet add package Alva.ServiceKit.IdentityServiceLightweight helper interface and implementations for accessing information about the currently authenticated user.
This package is part of the shared helper library set: Alva.ServiceKit.*
Designed for use in ASP.NET Core applications, including background services and Entity Framework Core contexts.
Install via NuGet:
.NET CLI
dotnet add package Alva.ServiceKit.IdentityService
PMC
NuGet\Install-Package Alva.ServiceKit.IdentityServic
Program.cs
builder.Services.AddTransient<IUserService, UserService>();
For background jobs or system-level operations, you may use the admin implementation:
builder.Services.AddTransient<IUserService>(
_ => new UserServiceAdmin("admin")
);
AppDbContext.cs
public class AppDbContext : DbContext
{
private readonly IUserService? _userService;
public AppDbContext(
DbContextOptions<AppDbContext> options,
IUserService? userService = null)
: base(options)
{
_userService = userService;
}
private void UpdateBaseEditedEntity()
{
var currentUser = _userService?.GetCurrentUserName();
foreach (EntityEntry<IBaseEditedEntity> entry
in ChangeTracker.Entries<IBaseEditedEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = currentUser;
entry.Entity.Created = DateTime.Now;
entry.Entity.ModifiedBy = currentUser;
entry.Entity.Modified = DateTime.Now;
break;
case EntityState.Modified:
entry.Entity.ModifiedBy = currentUser;
entry.Entity.Modified = DateTime.Now;
break;
}
}
}
}
public interface IUserService
{
string? GetCurrentUserName();
ClaimsPrincipal? GetCurrentUser();
}
Retrieves user information from the current HTTP context.
public string? GetCurrentUserName()
{
return _context.HttpContext?.User?.Identity?.Name;
}
public ClaimsPrincipal? GetCurrentUser()
{
return _context.HttpContext?.User;
}
System-level implementation for background tasks, migrations, or administrative actions.
public UserServiceAdmin(string? username = "admin")
{
_username = username ?? "admin";
}
public string GetCurrentUserName()
{
return _username;
}
public ClaimsPrincipal GetCurrentUser()
{
return new ClaimsPrincipal();
}
CreatedBy / ModifiedBy fieldsMIT