Get current windows user in Blazor Server

2k views Asked by At

I want to get the name of the current Windows user for my Blazor Server project.

I tried it via HttpContext, which is unreliable, according to this github issue.

Then I went with the MS documentation, without success.

Still returned null for User

At this point I'm wondering if it's my incompetence or something with my whole idea of using Blazor Server for this.

This is pretty much all the code:

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

There is also the part from the docu with the user.Identity.Name, but since I dont even get the claims, as of now, I am lost with what to do.

Edit 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));
    }
}
1

There are 1 answers

0
Pawel On

In your .razor file:

<AuthorizeView>
    Hello, @context.User.Identity?.Name!
</AuthorizeView>

Or in your code-behind:

[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;
    }
}