Home > database >  UserID from AuthenticationStateProvider appears empty
UserID from AuthenticationStateProvider appears empty

Time:11-29

I am using AspNetCore Identity and trying to get the UserID of the currently logged in user using AuthenticationStateProvider. I am logging to the console the output however, the username outputs fine but the ID appears empty. The ID field is not empty in the db table. When printing all the claims the subs field seems to be the correct ID. Am I incorrectly retrieving the ID? The approach to retrieve the ID was suggested from another post I found; code is shown below. How might I retrieve the sub value which is the userID, in my page using AuthenticationStateProvider? Thanks in advance.

Retrieving UserID

 var user = (await ASP.GetAuthenticationStateAsync()).User;
 var UserStringId = user.FindFirst(c => c.Type.Equals(user.Identity.Name))?.Value;

Browser console output

USER ID: blazor.webassembly.js:1 
NAME: [email protected]

Sub is correct ID when looping through Claims

    var user = (await ASP.GetAuthenticationStateAsync()).User;
    var item = user.Claims;

    foreach(var x in item)
    {
        Console.WriteLine(x);
    }

Browser console output

s_hash: EQ_bVJS8n32qtUam0wZ1MA
sid: 2E6B597CC9644CFEFDD627532B761F02
sub: 5685a830-cb82-4b60-b459-c0852cc74563 // trying to retrieve this ID
//...
preferred_username: [email protected]
name: [email protected]

CodePudding user response:

Try:

user.FindFirst(c => c.Type == "sub")?.Value
  • Related