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
equalsTrue
.Identity.Name
holdsadmin
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);
Additional Info
section.