IdentityUserRole Extension in Identity 2.0

Thus, my system requires roles to have associated expiration dates. I implemented the Identity 2.0 framework and everything runs smoothly, but I ran into a problem that makes me doubt my framework.

public class ApplicationUserRole : IdentityUserRole { public override string UserId { get; set; } public override string RoleId { get; set; } public DateTime Expiry { get; set; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } static ApplicationDbContext() { Database.SetInitializer<ApplicationDbContext>(null); } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public DbSet<ApplicationUserRole> ApplicationUserRoles { get; set; } } 

It does what I want. It modifies the AspNetUserRoles table to add a third column, which is a DateTime called Expiry. I can add, update and delete expiration using ApplicationDBContext, everything works perfectly and well when editing users.

The problem occurs when creating an account. UserManager calls AddToRolesAsync, but accepts only two parameters: "User and role". I need him to take User, Role and Expiry.

Do I need to implement my own UserManager? This is like busting.

I can get around the problem by not allowing the choice of role / expiration when creating an account and just leaving it in edit mode. But I would really like to be able to create accounts and assign roles / expiration at the same time.

+4
source share
2 answers

Check out the video tutorial on using the asp.net ID using existing database tables below. I think you should tell the ApplicationUser table that you have a new field in the ApplicationUserRole table. To do this, you need to follow the binding to the object structure of the object.

Part 1 - https://www.youtube.com/watch?v=elfqejow5hM

Part 2 - https://www.youtube.com/watch?v=JbSqi3Amatw

You do not need to implement your own userManager, but you must change it. Hope you can use this example to support your needs.

+2
source

I know that this has already been answered - but in case someone is interested, but instead of using UserManager.AddToRolesAsync, I got stuck on new roles and used the Role.Add () method of User ; So:

 var user = db.Users.Find(userId); foreach (string roleName in newRoles) { string roleId = RoleManager.FindByName(roleName).Id; var appUserRole = new ApplicationUserRole { UserId = user.Id, RoleId = roleId, CustomField1 = "value1", CustomField2 = "value2", .... }; user.Roles.Add(appUserRole); } 
+1
source

Source: https://habr.com/ru/post/977001/


All Articles