[英]How do I extend the authentication process in a blazor server side app?
[英]How to enable Windows authentication with server side Blazor
我有一个 Blazor 服务器端应用程序,它使用使用 IIS 的 Windows 身份验证。 该应用程序托管在 IIS 上,我已将应用程序池的网站标识更改为系统服务帐户。 (假设它是Domain\\sys_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
是Domain\\sys_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 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;
}
}
执行以下操作以在 Blazor 和 ASP.NET Core 控制器上为 IIS 和 Kestrel 启用 Windows 身份验证(适用于 ASP.NET Core 3.1 和 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();
如果下面提供了一个完整的例子,欢迎星星:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.