Search code examples
entity-frameworkasp.net-coreblazorblazor-client-sideblazor-webassembly

Getting UserId of current user Blazor webassembly


So I am writing a Blazor webassembly application, with asp.ner core Identity. I need to get the ID of the current user, not the username that the methods in Identy give.

The method

Context. User.identity.name

gives the username but I need the ID for a fk in a model/table.

I can't use the username as usernames might change.

I have searched the net, however I keep seeing just the username returned.

Any assistance will be greatly appreciated.


Solution

  • I use this with the boiler plate Identity Server:

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