Please I need assistance in implementing a custom way of assigning claims to authenticated users. On successful login,
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
//Get the user
ApplicationUser user = UserManager.FindByEmail(model.Email);
//Ends here
ClaimsIdentity identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = true }, identity);
I use the userId to fetch the role and other information about the user from the datastore. Thereafter, I need to add claims about the user with those information such as email, role, firstName, Lastname, gender, etc. before redirecting to the user dashboard. This is the way I try to do it but the problem is that even after adding the claims at the login method, I am not able to retrieve it at the _loginPartial razor view
For instance when I want to display the email claim value at the login partial like this
var claims = ClaimsPrincipal.Current.Claims;
var principal = (ClaimsPrincipal)Thread.CurrentPrincipal;
var email = principal.Claims.Where(c => c.Type == ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();
It returns null.
So, as a result, I can only access them on the same login method after adding them but I need to be able to access it from anywhere in the application. Please I will appreciate any assistance on how to be able to retrieve these claims anywhere else throughout the application.
Thank you.
Then in the view page
It will show the authenticated user firstName.
and import the following packages at the top of the page
You must add your claims before login not after. Consider this example:
Now since we have injected our claims while signing in, we have access to claims wherever we want:
Also you could add your claims in
ApplicationUser.GenerateUserIdentityAsync()
method. By adding your claims in this method you could useSignInManager.PasswordSignInAsync()
method to sign in users without any modification to defaultLogin
action method.are you not able to access
User.Identity
from the view?To retrieve claims for a user, it's been as simple as this for me:
var identity = (ClaimsIdentity) User.Identity
And then accessing
identity.Claims
and using LINQ to retrieve specific claims.In identity 2, this is done very differently and simply by creating a claims principal factory and then hooking it up in your startup ConfigureServices as below...
You would then hook it up in ConfigureServices just after calling AddIdentity like this...
Here is a very good article on the subject...
https://www.codeguru.com/csharp/csharp/cs_misc/security/asp.net-core-and-claim-based-security.html
The Claim property from IdentityUser gives you an ICollection with that collection you can call the following C# method: