entity-framework - 获取当前用户 Blazor webassembly 的 UserId
问题描述
所以我正在编写一个带有 asp.ner 核心标识的 Blazor webassembly 应用程序。我需要获取当前用户的 ID,而不是 Identy 中的方法提供的用户名。
方法
语境。用户身份名称
给出用户名,但我需要模型/表中 fk 的 ID。
我不能使用用户名,因为用户名可能会改变。
我已经搜索了网络,但是我一直看到返回的用户名。
任何帮助将不胜感激。
解决方案
我将它与样板身份服务器一起使用:
@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.";
}
}
}
推荐阅读
- python - 为什么我不能使用 '+' 在 Python 中合并字典?
- c++ - 使用可变参数模板时出现内部编译器错误
- teamcity - TeamCity安装成功后找不到newman包
- python - 如何保持 XML 标签的顺序,甚至使用 python 添加/删除标签
- angular - 带引导的角度芯片,不依赖于材料
- c++ - 如何处理来自 MIPI 相机的 12 位图像?
- regex - 正则表达式查找由字符串包围的任何字符串
- machine-learning - 有什么方法可以在特殊条件下逼近softmax概率?
- google-sheets - 使用多个条件的 Vlookup [Vlookup & Hlookup 结合]
- python - 使用 pywinauto 处理任务栏图标的上下文菜单