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;
}
CodePudding user response:
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 );