繁体   English   中英

如何使用服务器端 Blazor 启用 Windows 身份验证

[英]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.UserIdDomain\\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):

  1. 添加nuget引用:

Microsoft.AspNetCore.Authentication.Negotiate

Microsoft.AspNetCore.Components.Authorization

  1. 更新 Startup.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();
  1. 其余与使用其他身份验证方法相同。

如果下面提供了一个完整的例子,欢迎星星:)

使用 Windows 身份验证的 Blazor 和 ASP.NET Core 控制器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM