Reputation: 29159
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;
}
}
Upvotes: 4
Views: 5284
Reputation: 1357
Perform the following to enable Windows authentication on Blazor and ASP.NET Core Controllers for IIS and Kestrel (applies to ASP.NET Core 3.1 and ASP.NET 5):
Microsoft.AspNetCore.Authentication.Negotiate
Microsoft.AspNetCore.Components.Authorization
services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
// Windows authentication may not be applied with Kestrel without this line
services.AddAuthorization(options => options.FallbackPolicy = options.DefaultPolicy);
...
// Add the following below app.UseRouting()
app.UseAuthentication();
app.UseAuthorization();
A full example if provided below, stars are welcome :)
Blazor and ASP.NET Core controller using Windows authentication
Upvotes: 3