I am trying to get user information after login in ASP.NET Core 3.1 (information like name, email, id, ...).
Here is my code in login action
var claims = new List<Claim>()
{
new Claim(ClaimTypes.NameIdentifier, "NameIdentifire"),
new Claim(ClaimTypes.Name, "Name"),
new Claim(ClaimTypes.Email, "Email")
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
HttpContext.SignInAsync(principal);
In the views I only access the name by looking at @User.Identity.Name
. My question is: how to get other information user in different views?
You can create an helper class like this one:
internal static class ClaimsPrincipalExtensions
{
internal static string GetEmail(this ClaimsPrincipal claimsPrincipal)
=> claimsPrincipal.FindFirstValue(ClaimTypes.Email);
internal static string GetFirstName(this ClaimsPrincipal claimsPrincipal)
=> claimsPrincipal.FindFirstValue(ClaimTypes.Name);
internal static string GetLastName(this ClaimsPrincipal claimsPrincipal)
=> claimsPrincipal.FindFirstValue(ClaimTypes.Surname);
internal static string GetPhoneNumber(this ClaimsPrincipal claimsPrincipal)
=> claimsPrincipal.FindFirstValue(ClaimTypes.MobilePhone);
internal static string GetUserId(this ClaimsPrincipal claimsPrincipal)
=> claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier);
}
and use it like:
_profileModel.Email = user.GetEmail();
_profileModel.FirstName = user.GetFirstName();
_profileModel.LastName = user.GetLastName();
_profileModel.PhoneNumber = user.GetPhoneNumber();
This code is from a Blazor WASM application, but the code is about the same for ASP.NET Core.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With