Search code examples
blazoridentity

Get the ID of the current logged in user with Blazor Server


I have a Blazor Server application and need to get the current user ID. Its easy to get the email and the user name, but not the ID. It was so easy in .net core 2.2. Why they did not expose the ID is beyond me. I am using .net core 5.0.


Solution

  • I've needed to do this recently, but in a newer Blazor Web App, using .Net 8.0, so thought I'd add my more recent example here.

    I didn't want to copy/paste the same code into multiple pages, so came up with this:

    Create the interface:

    public interface IUserIdentityProcessor
    {
        Task<string?> GetCurrentUserId();
    }
    

    Create the class:

    using Microsoft.AspNetCore.Components.Authorization;
    
    public class UserIdentityProcessor : IUserIdentityProcessor
    {
        private readonly AuthenticationStateProvider _authenticationStateAsync;
    
        public UserIdentityProcessor(AuthenticationStateProvider authenticationStateAsync)
        {
            this._authenticationStateAsync = authenticationStateAsync;
        }
    
        public async Task<string?> GetCurrentUserId()
        {
            var authstate = await this._authenticationStateAsync.GetAuthenticationStateAsync();
    
            if (authstate == null)
            {
                return null;
            }
    
            var user = authstate.User;
    
            return user.FindFirst(u => u.Type.Contains("nameidentifier"))?.Value;
        }
    }
    

    Add the IoC line to your Program.cs:

    builder.Services.AddScoped<IUserIdentityProcessor, UserIdentityProcessor>();
    

    In your Blazor RazorComponent, add the using statement to the top of the page:

    @inject IUserIdentityProcessor _userIdentityProcessor
    

    ...add this to your page load:

    protected override async Task OnInitializedAsync()
    {
        var userId = this._userIdentityProcessor.GetCurrentUserId();
    }
    

    The result is a reusable class to get the user's Id (guid) and return it as a string. This can be called from a number of razor components/pages, and expanded to return more details from the user object, if needed.