我想为我的Blazor Server项目获取当前Windows用户的名称。
我通过HttpContext进行了尝试,根据github问题的说法,这是不可靠的。
然后我和MS文档一起去了,但没有成功。
仍然为用户返回null
在这一点上,我想知道是否是我的无能,或与我的整个想法使用Blazor为这一点。
这是几乎所有的代码:
@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:
Startup.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));
}
}发布于 2022-04-04 17:11:42
在您的.razor文件中:
<AuthorizeView>
Hello, @context.User.Identity?.Name!
</AuthorizeView>或者在你的代码背后:
[Inject]
AuthenticationStateProvider? AuthenticationStateProvider { get; set; }
public string? CurrentUserName { get; set; }
protected override async Task OnInitializedAsync()
{
if (AuthenticationStateProvider is not null)
{
var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
CurrentUserName = authenticationState.User.Identity?.Name;
}
}https://stackoverflow.com/questions/65236449
复制相似问题