我有一个Blazor服务器端应用程序,它使用IIS的Windows身份验证。该应用程序托管在 IIS 上,我已将应用程序池的网站标识更改为系统服务帐户。(说是Domainsys_account
(。
以下代码在LoginDisplay.razor
中。它可以显示打开网页的用户的正确标识。
<AuthorizeView>
<Authorized>
@{
var identity = (System.Security.Principal.WindowsIdentity)context.User.Identity;
}
Hello, @identity!
</Authorized>
<NotAuthorized>
You are not authorized.
</NotAuthorized>
</AuthorizeView>
我需要在 C# 代码中获取当前标识。因此,将创建以下类和接口。
public interface ICurrentUserService
{
string UserId { get; }
}
public class CurrentUserService : ICurrentUserService
{
public CurrentUserService()
{
UserId = WindowsIdentity.GetCurrent().Name;
}
public string UserId { get; }
}
它被添加到服务中作为
public void ConfigureServices(IServiceCollection services)
{
// ....
services.AddScoped<ICurrentUserService, CurrentUserService>();
但是,在下面的代码中。_currentUserService.UserId
Domainsys_account
而不是访问网站的人的 ID?如何获取当前登录用户的身份?
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 Domainsys_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 Domainsys_account instead of the id of the person logged in?
return Task.CompletedTask;
}
}
执行以下操作以在适用于 IIS 和 Kestrel 的 Blazor 和 ASP.NET 核心控制器上启用 Windows 身份验证(适用于 ASP.NET 核心 3.1 和 ASP.NET 5(:
- 添加 nuget 引用:
Microsoft.AspNetCore.Authentication.Negotiate
Microsoft.AspNetCore.Components.Authorization
- >更新启动.cs
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();
- 其余部分与使用其他身份验证方法相同。
下面提供了一个完整的例子,欢迎星星:)
使用 Windows 身份验证的 Blazor 和 ASP.NET 核心控制器