asp.net - 获取 Blazor Server 中的当前 windows 用户
问题描述
我想为我的 Blazor Server 项目获取当前 Windows 用户的名称。
根据this github issue ,我通过不可靠的HttpContext进行了尝试。
然后我使用了MS 文档,但没有成功。
仍然为用户返回 null
在这一点上,我想知道这是我的无能还是我使用 Blazor Server 的整个想法。
这几乎是所有代码:
@page "/"
@using System.Security.Claims
@using Microsoft.AspNetCore.Components.Authorization
@inject AuthenticationStateProvider AuthenticationStateProvider
<h3>ClaimsPrincipal Data</h3>
<button @onclick="GetClaimsPrincipalData">Get ClaimsPrincipal Data</button>
<p>@_authMessage</p>
@if (_claims.Count() > 0)
{
<ul>
@foreach (var claim in _claims)
{
<li>@claim.Type: @claim.Value</li>
}
</ul>
}
<p>@_surnameMessage</p>
@code {
private string _authMessage;
private string _surnameMessage;
private IEnumerable<Claim> _claims = Enumerable.Empty<Claim>();
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;
_surnameMessage =
$"Surname: {user.FindFirst(c => c.Type == ClaimTypes.Surname)?.Value}";
}
else
{
_authMessage = "The user is NOT authenticated.";
}
}
文档中还有 user.Identity.Name 的部分,但由于我什至没有得到索赔,到目前为止,我不知道该怎么做。
编辑1:
启动.cs
public class CustomAuthStateProvider : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync()
{
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, "mrfibuli"),
}, "Fake authentication type");
var user = new ClaimsPrincipal(identity);
return Task.FromResult(new AuthenticationState(user));
}
}
解决方案
推荐阅读
- apache-kafka - 如何增加卡夫卡消费者没有
- android - 刷卡时关闭卡片视图
- java - Java 正则表达式仅返回单个匹配项
- java - 当我为 SAML2.0 生成元数据并在 ADFS 上配置它时,它的有效期只有 3 个月
- r - R在使用read_excel导入期间更改excel值
- javascript - 无需单击即可在 ReactJS 中打开模态
- java - Java中的文件阅读器
- c++ - 如何在 qml 中向 QAbstractVideoFilter 发送参数?
- python - IndexError:列表索引超出范围。无法理解问题出在哪里?
- javascript - JavaScript Arrays .push() 未按预期工作