【问题标题】:How to get username of requesting user not app pool under windows auth如何在windows auth下获取请求用户的用户名而不是应用程序池
【发布时间】:2020-10-21 05:04:48
【问题描述】:

使用 Blazor 服务器应用程序。

我有应用程序池作为域帐户运行,但我需要用户名来执行请求。 使用它时,我会改为获取应用程序池的名称。

CallingUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split(new char[] { '\\' })[1];

更新 这篇文章帮助了我 Get Current User in a Blazor component

另外,还需要在 IIS 中启用 Websocket。直到我发布到测试服务器才发现。

【问题讨论】:

  • 有什么更新吗?我的回复能回答你的问题吗?
  • 这很有帮助,因为我在其他几个来源中看到了您的方法。但是,我最终使用了另一篇文章中列出的方法。请参阅上面的更新...

标签: asp.net-core blazor-server-side


【解决方案1】:

如果你想在服务器端获取登录用户。您应该将服务作为范围,然后您可以将AuthenticationStateProvider 注入服务。

然后就可以获取当前登录用户了。

详情,您可以参考以下代码: 公共类 WeatherForecastService { 私有只读 AuthenticationStateProvider _authenticationStateProvider;

     public WeatherForecastService(AuthenticationStateProvider authenticationStateProvider) {

        _authenticationStateProvider = authenticationStateProvider;
    }

public string GetCurrentUserName() {
      var provider=  _authenticationStateProvider.GetAuthenticationStateAsync();
        return provider.Result.User.Identity.Name;
    
    } 
 }

据我所知,如果你想获取当前登录用户,你可以尝试使用AuthenticationStateProvider服务。

内置的AuthenticationStateProvider服务从ASP.NET Core的HttpContext.User获取认证状态数据。

你可以注入AuthenticationStateProvider AuthenticationStateProvider然后使用AuthenticationStateProvider.GetAuthenticationStateAsync获取用户状态,最后你可以使用user.Identity.Name获取当前用户名。

更多细节,您可以参考以下代码:

@page "/counter"
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider


<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

<hr />
<button class="btn btn-primary" @onclick="GetUserName">Click me</button>

<p>Current Login User = @Username</p>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }

    private string Username = string.Empty;
    private async Task GetUserName()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;
        Username = user.Identity.Name;

    }

}

结果:

【讨论】:

    猜你喜欢
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 2019-01-09
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    相关资源
    最近更新 更多