I'm working on an authentication system that uses ASP.NET Identity with Entity Framework, and I want to have a few claims that are computed values instead of being hardcoded into the claims table.
When a user logs in, how can I add dynamic claims to that login session without actually adding them to the claims table?
For example, I may want to store each user's DOB, but I want add IsBirthday as a claim if the login date matches the user's DOB. I don't want to have to store a "IsBirthday" claim for each user since it changes daily for everyone.
In my code, I use this to log in:
var signInResult = await SignInManager.PasswordSignInAsync(username, password, false, false);
After this is called I can reference the ClaimsPrincipal, but the Claims property is an IEnumerable, not a List, so I can't add to it.
EDIT: I should also mention I am using the Microsoft.AspNet.Identity.Owin libraries.
OK, everyone, I did a bit of digging into the classes provided in ASP.NET Identity and found the one I needed to override. The SignInManager class has a CreateUserIdentityAsync method that does exactly what I was wanting. The following code added the IsBirthday claim to my identity but didn't store it in the database.
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
public override async Task<System.Security.Claims.ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
var identity = await base.CreateUserIdentityAsync(user);
identity.AddClaim(new System.Security.Claims.Claim("IsBirthday", user.DOB.GetShortDateString() == DateTime.Now.GetShortDateString()));
return identity;
}
// ... EXCLUDING OTHER STUFF LIKE CONSTRUCTOR AND OWIN FACTORY METHODS ...
}
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