首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Blazor Server中获取当前windows用户

在Blazor Server中获取当前windows用户
EN

Stack Overflow用户
提问于 2020-12-10 14:28:47
回答 1查看 1K关注 0票数 1

我想为我的Blazor Server项目获取当前Windows用户的名称。

我通过HttpContext进行了尝试,根据github问题的说法,这是不可靠的。

然后我和MS文档一起去了,但没有成功。

仍然为用户返回null

在这一点上,我想知道是否是我的无能,或与我的整个想法使用Blazor为这一点。

这是几乎所有的代码:

代码语言:javascript
复制
@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

代码语言:javascript
复制
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));
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-04-04 17:11:42

在您的.razor文件中:

代码语言:javascript
复制
<AuthorizeView>
    Hello, @context.User.Identity?.Name!
</AuthorizeView>

或者在你的代码背后:

代码语言:javascript
复制
[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;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65236449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档