【问题标题】:Getting UserId of current user Blazor webassembly获取当前用户 Blazor webassembly 的 UserId
【发布时间】:2020-11-16 02:53:36
【问题描述】:

所以我正在编写一个带有 asp.ner 核心标识的 Blazor webassembly 应用程序。我需要获取当前用户的 ID,而不是 Identy 中的方法给出的用户名。

方法

上下文。 User.identity.name

提供用户名,但我需要模型/表中 fk 的 ID。

我不能使用用户名,因为用户名可能会改变。

我已经在网上搜索过,但我总是看到返回的用户名。

我们将不胜感激。

【问题讨论】:

  • 这些答案都没有帮助我,为什么仅仅获取用户 ID 就这么复杂?

标签: entity-framework asp.net-core blazor blazor-client-side blazor-webassembly


【解决方案1】:

我将它与样板身份服务器一起使用:

@page "/claims"
@inject AuthenticationStateProvider AuthenticationStateProvider

<h3>ClaimsPrincipal Data</h3>

<p>@_authMessage</p>

@if (_claims.Count() > 0)
{
    <table class="table">
        @foreach (var claim in _claims)
        {
            <tr>
                <td>@claim.Type</td>
                <td>@claim.Value</td>
            </tr>
        }
    </table>
}

<p>@_userId</p>

@code {
    private string _authMessage;       
    private string _userId;
    private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();

    protected override async Task OnParametersSetAsync()
    {
        await GetClaimsPrincipalData();
        await base.OnParametersSetAsync();
    }

    private async Task GetClaimsPrincipalData()
    {
        var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
        var user = authState.User;

        if (user.Identity.IsAuthenticated)
        {
            _authMessage = $"{user.Identity.Name} is authenticated.";
            _claims = user.Claims;
            _userId = $"User Id: {user.FindFirst(c => c.Type == "sub")?.Value}";
        }
        else
        {
            _authMessage = "The user is NOT authenticated.";
        }
    }
}

【讨论】:

  • 我建议在控制器中提取 ID,因为这比信任客户端发布内容更安全。
  • @ErikThysell 这是原理的扩展方法。
  • OP 想要的是 ID 而不是名称...“sub”应该是什么声明?
【解决方案2】:

在 Startup.cs 中,在 ConfigureServices 中添加以下行

services.AddHttpContextAccessor();

在您的 Blazor 组件中,在文件顶部添加以下行

@using System.Security.Claims
@inject IHttpContextAccessor HttpContextAccessor

在您的方法中,添加以下行以获取 UserId

var principal = HttpContextAccessor.HttpContext.User;
var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);

【讨论】:

  • 这在 Blazor Server dotnet 5 上实现了完美的技巧
  • 这是用于 WASM 还是服务器端?
【解决方案3】:

不是答案,只是关于使用断点找到答案的提示。我的网站是 Blazor Server,所以很可能情况有所不同——就我而言,Brian Parker 的解决方案对我不起作用,所以我做了以下操作:

var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
if (true) {} // or any other code here, breakpoint this line

如果您在检索用户后立即设置断点,运行应用程序并在中断时将用户变量悬停在代码中,它将弹出完整的对象。通过悬停各个字段,您可以进行调查。我发现声明类型字符串很长,例如“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier”

所以对我有用的答案是:

var user = (await AuthenticationStateProvider.GetAuthenticationStateAsync()).User;
string userId = user.FindFirst(c => c.Type.Contains("nameidentifier"))?.Value;

我的观点是,当文档很复杂,或者技术变化很快,以至于一天的正确答案是第二天的错误线索时,你可以通过使用 VS 挖掘来获得很多。

希望对某人有所帮助。 :D

【讨论】:

    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 2021-10-22
    • 2021-03-03
    相关资源
    最近更新 更多