31

In AuthController when authenticating I create a few Claims - UserID is one of them.

...
Subject = new ClaimsIdentity(new[]
{
  new Claim(ClaimTypes.Name, user.UserName),
  new Claim("UserID", user.Id.ToString()),
})

When Angular app makes request I am able to fetch UserID in another controller

Claim claimUserId = User.Claims.SingleOrDefault(c => c.Type == "UserID");

The ControllerBase.User instance holds .Identity object which in turn holds Claims collection.

  • Identity.IsAuthenticated equals True.

  • Identity.Name holds admin string (name of the relevant user).

If I try to fetch user like this:

var user = await UserManager.GetUserAsync(HttpContext.User)

the user is null.

Perhaps, I forgot to add some extra claim?

Or maybe, once I'm using JWT - I should override the default UserManager functionality so it fetches user by claim which holds UserID?

Or maybe there's a better approach?


Additional info:

The Identity is registered as follows

services.AddIdentity<ApplicationUser, ApplicationRole>()
    .AddEntityFrameworkStores<AppDbContext>()
    .AddDefaultTokenProviders();

ApplicationUser.Id field is of bigint (or in C# of long) type

Also, I create users in EF Seed Data with UserManager which is resolved using ServiceProvider

_userManager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
    ...
        adminUser.PasswordHash = new PasswordHasher<ApplicationUser>().HashPassword(adminUser, "123qwe");
        _userManager.CreateAsync(adminUser);
2
  • Could you share how you register Identity? Jul 1, 2018 at 10:04
  • hi @AlexRiabov, just answered your question, the code under Additional Info section. Jul 1, 2018 at 13:24

3 Answers 3

54

UserManager.GetUserAsync internally uses UserManager.GetUserId to retrieve the user id of the user which is then used to query the object from the user store (i.e. your database).

GetUserId basically looks like this:

public string GetUserId(ClaimsPrincipal principal)
{
    return principal.FindFirstValue(Options.ClaimsIdentity.UserIdClaimType);
}

So this returns the claim value of Options.ClaimsIdentity.UserIdClaimType. Options is the IdentityOptions object that you configure Identity with. By default the value of UserIdClaimType is ClaimTypes.NameIdentifier, i.e. "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier".

So when you try to use UserManager.GetUserAsync(HttpContext.User), where that user principal has a UserID claim, the user manager is simply looking for a different claim.

You can fix this by either switchting to the ClaimTypes.NameIdentifier:

new ClaimsIdentity(new[]
{
    new Claim(ClaimTypes.Name, user.UserName),
    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
})

Or you configure Identity properly so it will use your UserID claim type:

// in Startup.ConfigureServices
services.AddIdentity(options => {
    options.ClaimsIdentity.UserIdClaimType = "UserID";
});
5
  • 1
    Alternatively..., if userId is not available, one can use userManager.FindByNameAsync(username) instead if that fits the business requirement. Sep 26, 2018 at 5:37
  • Simply doing new Claim(ClaimTypes.NameIdentifier, user.Id) worked for me. Previously had this as user.UserName. Didn't realize the "name identifier" would be an Id. Who woulda thunk.
    – mwilson
    Apr 11, 2020 at 23:39
  • @mwilson How you use the claims mostly depends on your application. There are different ways to approach this, and it also depends on what your id is.
    – poke
    Apr 12, 2020 at 11:41
  • Great solution. In my case, the Startup.ConfigureServices solution worked for me. Setting a breakpoint in the controller and navigating through the User->claims helped me realize which claim type my organization was using to get the userid. Then setting options.ClaimsIdentity.UserIdClaimType = ClaimTypes.[option] did it for me.
    – eaglei22
    Apr 28, 2021 at 19:34
  • UserManager.GetUserAsync eventually calls the method FindByIdAsync of the IUserStore implementation which is helpful to know if you need to debug a custom IUserStore implementation.
    – ackh
    Oct 20, 2021 at 12:21
2

When you create Claims, you just need to do like:

 List<Claim> claims = new()
 {
    new Claim(ClaimTypes.NameIdentifier, user.Id),  // This line is important.
    new Claim(ClaimTypes.Email, user.Email),
    new Claim(JwtRegisteredClaimNames.Jti, jti)
 };
2

For me it was a tutorial that gave bad advice, it assigned a "general description" to the "sub" claim of the JWT-token.

A claim entry for ClaimTypes.NameIdentifier is automatically created from the "sub" claim in the JWT auth library, so it ended up double. One with incorrect value and one with correct.

This was the incorrect implementation:

   private Claim[] CreateClaims(IdentityUser user)
    {
        return new[] {
            new Claim(ClaimTypes.NameIdentifier, user.Id),
            new Claim(ClaimTypes.Name, user.UserName),
            new Claim(ClaimTypes.Email, user.Email),
            new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
        };
    }

This is the correct implementation:

private Claim[] CreateClaims(IdentityUser user)
{
    return new[] {
        new Claim(ClaimTypes.Name, user.UserName),
        new Claim(ClaimTypes.Email, user.Email),
        new Claim(JwtRegisteredClaimNames.Sub, user.Id),
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
    };
}

How the claims look with the correct implementation:

Claims

1
  • I must have followed the same tutorial! Thanks so much for posting when you worked it out! Removing name identifier and replacing Sub value with the userId solved it for me!
    – James
    Jun 6 at 13:01

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.