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

  • There are a couple ways to do it. Here's one I found with a little hacking around. I like it because it only requires a single injection, and because ASP also handles roles. Surprisingly, "nameidentifier" is the UserId (which is a GUID) in a standard EF Core login:

    @inject AuthenticationStateProvider _authenticationStateProvider
            
    @code {
        async Task<string> getUserId(){
            var user = (await _authenticationStateProvider.GetAuthenticationStateAsync()).User;
            var UserId = user.FindFirst(u => u.Type.Contains("nameidentifier"))?.Value;
            return UserId;
        }
    }
    

    I recommend in Visual Studio setting a break point after retrieving the user, and then hovering over it. That will allow you to inspect it and see all the little bits and pieces-- you'll be surprised how much neat information you can dig up in the User object!