【问题标题】:How to enable Windows authentication with server side Blazor如何使用服务器端 Blazor 启用 Windows 身份验证
【发布时间】:2020-04-11 11:30:07
【问题描述】:

我有一个使用 IIS 的 Windows 身份验证的 Blazor 服务器端应用程序。该应用程序托管在 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;
    }
}

【问题讨论】:

标签: c# asp.net asp.net-core iis blazor


【解决方案1】:

执行以下操作以在 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. 其余与使用其他身份验证方法相同。

如果在下面提供完整示例,欢迎加星 :)

Blazor and ASP.NET Core controller using Windows authentication

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2021-04-30
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多