Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding role to AspNetUserRoles table in ASP.NET Identity

I use ASP.NET Identity 2.0 in my MVC application and I want to assign 2 default roles to the user who login to the system for the first time by adding 2 records to the AspNetUserRoles table with UserId and RoleId. Is there a practical way to to this? Or do I have to add these default roles using DBContext and Entity Framework, etc. (I use EF Code First)? Any help would be appreciated.

like image 834
Jack Avatar asked Apr 05 '16 08:04

Jack


2 Answers

After creating the user record in Register post action

var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);

You can add the roles

await UserManager.AddToRoleAsync(user.Id, "role1");
await UserManager.AddToRoleAsync(user.Id, "role2");
like image 87
tmg Avatar answered Nov 15 '22 04:11

tmg


You could do a check in the AccountController, Register method (the one with the HttpPost), something like: if (!MyDbContext.Users.Any()) {...}

And if there are no users, assign roles to the newly created user with: UserManager.AddToRoleAsync

like image 29
Attila Szasz Avatar answered Nov 15 '22 03:11

Attila Szasz