0

Using the standard Blazor Server with individual accounts scaffolded by Microsoft, how do I access the logged in userId inside of a component? .NET 5.

I've tried tapping into AuthenticationStateProvider and using this to get it, but that returns null.

 var authState = await authenticationStateProvider.GetAuthenticationStateAsync();

        if (authState.User.Identity.IsAuthenticated)
        {
            var id = authState.User.FindFirst(c => c.Type == "nameidentifier")?.Value;
        }
2
  • Use ClaimTypes.NameIdentifier constant, not a magic string. Commented Oct 20, 2021 at 16:48
  • You can also use User.FindFirstValue(ClaimTypes.NameIdentifier) Commented Oct 20, 2021 at 16:50

1 Answer 1

1

The user information is stored in the ClaimsPrincipal. Here's a couple of extension methods I use:

public static long GetUserId( this ClaimsPrincipal principal )
{
    string val = principal.FindFirstValue( ClaimTypes.NameIdentifier );
    return long.Parse( val );
}

public static bool TryGetUserId( this ClaimsPrincipal principal, out long userId )
{
    if( principal.HasClaim( x => x.Type == ClaimTypes.NameIdentifier ) )
    {
        userId = principal.GetUserId();
        return true;
    }

    userId = -1;
    return false;
}

And usage would something along the lines of:

// from a controller
long id = User.GetUserId();

// from an HTTPContext, i.e., middleware
bool hasId = context.User.TryGetUserId( out long userId );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.