I have a Blazor Server-side application which uses Windows Authentication using IIS. The application is hosted on IIS and I've changed the Identity of the website of the application pools to a system service account. (Say it's Domain\sys_account).
The following code is in LoginDisplay.razor. It can display the correct Identity of the user who opens the web page.
<AuthorizeView>
<Authorized>
@{
var identity = (System.Security.Principal.WindowsIdentity)context.User.Identity;
}
Hello, @identity!
</Authorized>
<NotAuthorized>
You are not authorized.
</NotAuthorized>
</AuthorizeView>
I need to get the current identity in the C# code. So the following class and interface are created.
public interface ICurrentUserService
{
string UserId { get; }
}
public class CurrentUserService : ICurrentUserService
{
public CurrentUserService()
{
UserId = WindowsIdentity.GetCurrent().Name;
}
public string UserId { get; }
}
And it's added to services as
public void ConfigureServices(IServiceCollection services)
{
// ....
services.AddScoped<ICurrentUserService, CurrentUserService>();
However, in the following code. _currentUserService.UserId is Domain\sys_account instead of the id of the person who accesses the site? How to get the identity of current logged in user?
public class RequestLogger<TRequest> : IRequestPreProcessor<TRequest>
{
private readonly ILogger _logger;
private readonly ICurrentUserService _currentUserService;
public RequestLogger(ILogger<TRequest> logger, ICurrentUserService currentUserService)
{
_logger = logger;
_currentUserService = currentUserService; // _currentUserService.UserId is Domain\sys_account instead of the id of the person who accesses the site?
}
public Task Process(TRequest request, CancellationToken cancellationToken)
{
var name = typeof(TRequest).Name;
_logger.LogInformation("Request: {Name} {@UserId} {@Request}",
name, _currentUserService.UserId, request); // _currentUserService.UserId is Domain\sys_account instead of the id of the person logged in?
return Task.CompletedTask;
}
}