Blazor Get User Id

I have been trying to access the User_Id of a logged in user in a blazor page component. I have tried the suggested way of setting this up in Startup.cs.


    // Configure the scope
    options.Scope.Clear();
    options.Scope.Add("openid");
    options.SaveTokens = true;
    options.TokenValidationParameters = new TokenValidationParameters
    {
        NameClaimType = ClaimTypes.NameIdentifier
    };
    

In my page component i am using the following to get the authentication state.

[CascadingParameter] Task<AuthenticationState> authenticationStateTask { get; set; }

Following this I am trying to get the user id as Name from User.Identity but the value is null. For now I am getting it via


var authState = await authenticationStateTask;
var userId = authState.User.Claims.FirstOrDefault().Value;

Is there a way to set this up so the user id is populated in User.Identity.Name or am i better off doing it this way?

Hey there!

Unfortunately I don’t have that much of experience with Blazor but maybe this article of ours as well as a dedicated thread for it will be able to help:

Hi @michael.bird, maybe this post can help you.

1 Like

Thanks for sharing that Andrea!

1 Like