正在获取当前用户Blazor Web程序集的UserId



所以我正在编写一个Blazor webassembly应用程序,使用asp.ner核心Identity。我需要得到当前用户的ID,而不是Identi中的方法给出的用户名。

方法

上下文。User.identity.name

给出了用户名,但我需要模型/表中fk的ID。

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

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

如有任何协助,我们将不胜感激。

我将其与锅炉板Identity Server:一起使用

@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.";
}
}
}

在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,所以很可能情况有所不同——在我的情况下,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

最新更新