i want to create a new role for admin . i am using .net framework mvc 5 but when i run the application it does not create the user and does not save it in the database although the role with id is created successfully and i can see it through the database.
my code is written in startup.cs
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
CreateUserAndRoles();
}
public void CreateUserAndRoles()
{
ApplicationDbContext context = new ApplicationDbContext();
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
if (!roleManager.RoleExists("Admin"))
{
var role = new IdentityRole("Admin");
roleManager.Create(role);
var user = new ApplicationUser();
user.UserName = "admin";
user.Email = "admin#admin.com";
string password = "12345";
var newuser = userManager.Create(user, password);
if (newuser.Succeeded)
{
userManager.AddToRole(user.Id, "Admin");
}
}
}
}
Related
This question already has answers here:
How to seed an Admin user in EF Core 2.1.0?
(7 answers)
Closed 3 years ago.
I have managed to seed the admin's details like the username and password, so they appear in the table. However, the issue I am having is the role "admin" is not being saved anywhere in the table. Am I missing something here? I am new to asp.net core so I'm just trying to wrap my head around it.
Below is my seeding class:
public class ApplicationDbInitializer
{
public static void SeedUsers(UserManager<IdentityUser> userManager)
{
if (userManager.FindByEmailAsync("abc#outlook.com").Result == null)
{
IdentityUser user = new IdentityUser
{
UserName = "abc#outlook.com",
Email = "abc#outlook.com"
};
IdentityResult result = userManager.CreateAsync(user, "Passwordtest123!").Result;
if (result.Succeeded)
{
userManager.AddToRoleAsync(user, "Admin").Wait();
}
}
}
}
Below is my configure method signature:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<IdentityUser> userManager)
Below is me invoking my seed method:
ApplicationDbInitializer.SeedUsers(userManager);
Below is my add identity:
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<RestaurantWebContext>();
Is there something in the code that is missing, I can't see admin show up in the role table or the user table.
You need to seed the Roles as well, then link the User to the Role you want.
Check this answer for more information of how you can seed the data.
You can view my full code here
Below is an example
var user = new User
{
Id = new Guid("a1add451-7dd2-46fd-9877-1996e3f1fb4c").ToString(),
Email = "",
NormalizedEmail = "".ToUpper(),
UserName = "",
NormalizedUserName = "tony5".ToUpper(),
EmailConfirmed = true,
PhoneNumberConfirmed = true,
LockoutEnabled = false,
SecurityStamp = Guid.NewGuid().ToString()
};
using (var context = new ApplicationDbContext(
serviceProvider.GetRequiredService<DbContextOptions<ApplicationDbContext>>()))
{
var roles = new[]
{"Owner", "Administrator", "Editor", "ContentWriter"};
var roles1 = new[]
{"Administrator"};
var roles2 = new[]
{"Editor"};
var roles4 = new[]
{"Owner", "Administrator"};
if (!context.Roles.Any())
{
foreach (var role in roles)
{
var roleStore = new RoleStore<ApplicationRole>(context);
await roleStore.CreateAsync(new ApplicationRole
{
Name = role,
NormalizedName = role.ToUpper()
});
}
}
if (!context.Users.Any())
{
await SeedUser(user, context, serviceProvider, roles4);
}
}
private static async Task SeedUser(
User user,
ApplicationDbContext context,
IServiceProvider serviceProvider,
string[] roles)
{
var password = new PasswordHasher<User>();
var hashed = password.HashPassword(user, "123456");
user.PasswordHash = hashed;
var userStore = new UserStore<User>(context);
await userStore.CreateAsync(user);
await EnsureRole(serviceProvider, user.Email, roles);
await context.SaveChangesAsync();
}
I have a controller that checks the claims to get the current user's username, role, like so:
var identity = ClaimsPrincipal.Current.Identities.First();
bUsername = identity.Claims.First(c => c.Type == "Username").Value;
role = identity.Claims.First(c => c.Type == "Role").Value;
These details are set when the user first logs in. When I try to test this method, if falls over at the lines of code above because there was no login. So I tried creating a principal in the TestInitialization so it would always be available for the controllers asking for the username in the above way:
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Name, "Test Name"),
new Claim(ClaimTypes.NameIdentifier, "test"),
new Claim("Username", "test"),
new Claim("Role","ADMIN")
};
var identity = new ClaimsIdentity(claims, "TestAuthType");
var claimsPrincipal = new ClaimsPrincipal(identity);
I breakpointed the code, and it hits this code before it hits the above code, so it seems like it is creating the principal before checking for the username, however it still falls over on the username check, it's still not finding anything.
Can anybody advise me on what I'm doing wrong?
So, based on the advice of #DavidG, I ended up abstracting the claim stuff out of the controller. Posting this here for anyone else that needs help in the future. I created the following classes:
ICurrentUser
public interface ICurrentUser
{
User GetUserDetails();
}
CurrentUser
public class CurrentUser : ICurrentUser
{
public User GetUserDetails()
{
var user = new User();
try
{
var identity = ClaimsPrincipal.Current.Identities.First();
user.Username = identity.Claims.First(c => c.Type == "Username").Value;
user.Role = identity.Claims.First(c => c.Type == "Role").Value;
user.LoggedIn = identity.Claims.First(c => c.Type == "LoggedIn").Value;
return user;
}
catch (Exception)
{
return user;
}
}
}
Then I added it to my constructor like so:
public readonly ICurrentUser currentUser;
public readonly IUnitOfWork unitOfWork;
public HomeController(IUnitOfWork unitOfWork, ICurrentUser currentUser)
{
this.unitOfWork = unitOfWork;
this.currentUser = currentUser;
}
Then I use Ninject to inject it:
kernel.Bind<ICurrentUser>().To<CurrentUser>().InRequestScope();
Now it is loosely coupled to my controller, allowing me to mock it, like so:
[TestClass]
public class HomeControllerTest
{
private Mock<IUnitOfWork> _unitOfWorkMock;
private Mock<ICurrentUser> _currentUserMock;
private HomeController _objController;
[TestInitialize]
public void Initialize()
{
_unitOfWorkMock = new Mock<IUnitOfWork>();
_currentUserMock = new Mock<ICurrentUser>();
_currentUserMock.Setup(x => x.GetUserDetails()).Returns(new User { Username = "TEST", Role = "ADMIN", LoggedIn = "Y" });
_objController = new HomeController(_unitOfWorkMock.Object, _currentUserMock.Object);
}
}
I have added an additional property to ApplicationUserRole as follows:
public class ApplicationUserRole : IdentityUserRole<int>
{
public string RoleAssigner { get; set; }
}
Now i am to assign a role to an user as follows:
[HttpPost]
public ActionResult Create(UserRoleViewModel userRoleViewModel)
{
if (ModelState.IsValid)
{
using (var context = new ApplicationDbContext())
{
var userRole = new ApplicationUserRole
{
UserId = userRoleViewModel.UserId,
RoleId = userRoleViewModel.RoleId,
RoleAssigner = userRoleViewModel.RoleAssigner
};
context.ApplicationUserRoles.Add(userRole);
context.SaveChanges();
return RedirectToAction("Index");
}
}
return View(userRoleViewModel);
}
This is working fine!!
Before adding additional "RoleAssigner" Property, I can assign a role to an user using AddToRoles() Method as follows:
[HttpPost]
public ActionResult Create(UserRoleViewModel userRoleViewModel)
{
if (ModelState.IsValid)
{
UserManager.AddToRoles(userRoleViewModel.Id, userRoleViewModel.RoleName);
return RedirectToAction("Index");
}
return View(userRoleViewModel);
}
My question is: After adding an additional Property like "RoleAssigner", Is there any way to assign a role to an user using AddToRoles() method which will also insert the additional "RoleAssigner" value for "RoleAssigner" column in the database also.
Edit with working example:
I think you can do that by creating an extension method at IdentityConfig.
I did something similar to find user by username or phone number
In what I'm able to understand you want to call UserManager.AddToRoles(...) and
fill the new role property.
to do that( in similar to the example before ) you need an extension to user manager. you do it like this:
public static class UserManagerExtens
{
public static IdentityResult AddToRole(this ApplicationUserManager userManager,string userId,string[] roles,string assigner)
{
try
{
ApplicationUserRole role = null;
using (ApplicationDbContext context = new ApplicationDbContext())
{
foreach (var item in roles)
{
role = new ApplicationUserRole();
role.UserId = userId;
role.RoleAssigner = assigner;
role.RoleId = item;
context.AspNetUserRoles.Add(role);
}
context.SaveChanges();
}
return new IdentityResult() { };
}
catch (Exception ex)
{
return new IdentityResult(ex.Message);
}
}
}
That is a working example, using UserManager you can call it with definded
parameters like:
string[] roles = new string[] { /*your roles here*/ };
UserManager.AddToRole(/*UserIdHere*/, roles, /*assigerId here*/);
Similar to this you can implement async or other methods of UserManager.
If you are using asp.net core application in startup.cs you should inject proper store models
services.AddIdentity<ApplicationUser, YOURROLEMODEL(ApplicationUserRole )>()
If you are using asp.net application there should be IdentityConfig.cs file You should implement your UserStore which will get you RoleModel as generic. You can see I have created AppUserStore class and it gets MyIdentityRole model as a generic Type. And changed ApplicationUserManager to use my AppUserStore class.
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new AppUserStore(context.Get<ApplicationDbContext>()));
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<ApplicationUser>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = true;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 5;
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
public class AppUserStore :
UserStore<ApplicationUser, MyIdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>, IUserStore<ApplicationUser>
{
public AppUserStore(DbContext context) : base(context)
{
}
}
public class MyIdentityRole : IdentityRole
{
public string MyProperty { get; set; }
}
I have finished doing this tutorial/sample, on how to use MySQL database with ASP.NET identity:
http://www.asp.net/identity/overview/getting-started/aspnet-identity-using-mysql-storage-with-an-entityframework-mysql-provider
Now I would like to add functionality wich creates Admin user on start with role Admin. In the past I was using SimpleMembership and local 'SQL Server Database'and it was quite simple, now I'm trying to do this by adding user in 'MySqlInitializer'. Here's a code I'm trying to make work:
MySqlInitializer
namespace IdentityMySQLDemo
{
public class MySqlInitializer : IDatabaseInitializer<ApplicationDbContext>
{
public void InitializeDatabase(ApplicationDbContext context)
{
if (!context.Database.Exists())
{
// if database did not exist before - create it
context.Database.Create();
}
else
{
// query to check if MigrationHistory table is present in the database
var migrationHistoryTableExists = ((IObjectContextAdapter)context).ObjectContext.ExecuteStoreQuery<int>(
string.Format(
"SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = '{0}' AND table_name = '__MigrationHistory'",
"17817412_kontadb"));
// if MigrationHistory table is not there (which is the case first time we run) - create it
if (migrationHistoryTableExists.FirstOrDefault() == 0)
{
context.Database.Delete();
context.Database.Create();
}
}
Seed(context);
}
protected void Seed(ApplicationDbContext context)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
const string name = "admin#example.com";
const string password = "Password";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
var roleresult = roleManager.Create(role);
}
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
var result = userManager.Create(user, password);
result = userManager.SetLockoutEnabled(user.Id, false);
}
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
}
}
}
IdentityModels
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace IdentityMySQLDemo.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
static ApplicationDbContext()
{
Database.SetInitializer(new MySqlInitializer());
}
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
I don't know why it don't want to create Admin user on application start, I was trying to move this code to "Configuration" or 'MySQLConfiguration" in Migrations folder. I was also trying to create all table first and than add Admin user with this, but it still didn't work. Please tell me where is my stupid mistake in this code?
It looks like ther maybe a missing context.SaveChanges() or three.
Is the problem with your seed method? If the issue is when your running your update-database command in the NuGet package manager console, if there is no call to context.SaveChanges() then it won't update the DB.
You'll also need to call it 3 times..
after the role is created
after the user is created
after the user is assigned to the role
I'm a relatively newbie myself to C# / ASP.NET MVC so am not 100% if this is the correct fix as unable to test my thoughts currently, but seems to be a similar problem I've faced in the past.
UPDATE
I've had a play around and this successfully updated the 3 tables as part of the seed method.
I think one of the other problems is that rather than calling a method in a couple of places, you were just assigning them into a variable and then not using. For example in this snippet:
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
var result = userManager.AddToRole(user.Id, role.Name);
}
I changed it to:
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
userManager.AddToRole(user.Id, role.Name);
}
Thus removing var result =
Here is the full code:
protected override void Seed( MySqlInitializer context)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext("DefaultConnection")));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext("DefaultConnection")));
const string name = "admin#example.com";
const string password = "Password";
const string roleName = "Admin";
//Create Role Admin if it does not exist
var role = roleManager.FindByName(roleName);
if (role == null)
{
role = new IdentityRole(roleName);
roleManager.Create(role);
}
context.SaveChanges();
var user = userManager.FindByName(name);
if (user == null)
{
user = new ApplicationUser { UserName = name, Email = name };
userManager.Create(user, password);
userManager.SetLockoutEnabled(user.Id, false);
}
context.SaveChanges();
// Add user admin to Role Admin if not already added
var rolesForUser = userManager.GetRoles(user.Id);
if (!rolesForUser.Contains(role.Name))
{
userManager.AddToRole(user.Id, role.Name);
}
context.SaveChanges();
}
In some ways I would like to thank you as by helping you, I've helped myself :)
There is very little documentation about using the new Asp.net Identity Security Framework.
I have pieced together what I could to try and create a new Role and add a User to it. I tried the following: Add role in ASP.NET Identity
which looks like it may have gotten the info from this blog: building a simple to-do application with asp.net identity and associating users with to-does
I have added the code to a Database Initializer that is run whenever the model changes. It fails on the RoleExists function with the following error:
System.InvalidOperationException occurred in mscorlib.dll
The entity type IdentityRole is not part of the model for the current context.
protected override void Seed (MyContext context)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
// Create Admin Role
string roleName = "Admins";
IdentityResult roleResult;
// Check to see if Role Exists, if not create it
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
Any help is appreciated.
Here we go:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if(!roleManager.RoleExists("ROLE NAME"))
{
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
role.Name = "ROLE NAME";
roleManager.Create(role);
}
Verify you have following signature of your MyContext class
public class MyContext : IdentityDbContext<MyUser>
Or
public class MyContext : IdentityDbContext
The code is working for me, without any modification!!!
Here is the complete article describing how to create roles, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains the User interface, controller methods, etc.
http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc
In ASP.NET 5 rc1-final, I did following:
Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)
public class ApplicationRoleManager : RoleManager<IdentityRole>
{
public ApplicationRoleManager(
IRoleStore<IdentityRole> store,
IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
ILogger<RoleManager<IdentityRole>> logger,
IHttpContextAccessor contextAccessor)
: base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
{
}
}
To ConfigureServices in Startup.cs, I added it as RoleManager
services.
.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoleManager<ApplicationRoleManager>();
For creating new Roles, call from Configure following:
public static class RoleHelper
{
private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
{
if (!await roleManager.RoleExistsAsync(roleName))
{
await roleManager.CreateAsync(new IdentityRole(roleName));
}
}
public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
{
// add all roles, that should be in database, here
await EnsureRoleCreated(roleManager, "Developer");
}
}
public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
{
...
await roleManager.EnsureRolesCreated();
...
}
Now, the rules can be assigned to user
await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");
Or used in Authorize attribute
[Authorize(Roles = "Developer")]
public class DeveloperController : Controller
{
}
As an improvement on Peters code above you can use this:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (!roleManager.RoleExists("Member"))
roleManager.Create(new IdentityRole("Member"));
My application was hanging on startup when I used Peter Stulinski & Dave Gordon's code samples with EF 6.0. I changed:
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
to
var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));
Which makes sense when in the seed method you don't want instantiate another instance of the ApplicationDBContext. This might have been compounded by the fact that I had Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); in the constructor of ApplicationDbContext
Roles View Model
public class RoleViewModel
{
public string Id { get; set; }
[Required(AllowEmptyStrings = false)]
[Display(Name = "RoleName")]
public string Name { get; set; }
}
Controller method
[HttpPost]
public async Task<ActionResult> Create(RoleViewModel roleViewModel)
{
if (ModelState.IsValid)
{
var role = new IdentityRole(roleViewModel.Name);
var roleresult = await RoleManager.CreateAsync(role);
if (!roleresult.Succeeded)
{
ModelState.AddModelError("", roleresult.Errors.First());
return View();
}
return RedirectToAction("some_action");
}
return View();
}
I wanted to share another solution for adding roles:
<h2>Create Role</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<span class="label label-primary">Role name:</span>
<p>
#Html.TextBox("RoleName", null, new { #class = "form-control input-lg" })
</p>
<input type="submit" value="Save" class="btn btn-primary" />
}
Controller:
[HttpGet]
public ActionResult AdminView()
{
return View();
}
[HttpPost]
public ActionResult AdminView(FormCollection collection)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(collection["RoleName"]) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] });
}
return View();
}
If you are using the default template that is created when you select a new ASP.net Web application and selected Individual User accounts as Authentication and trying to create users with Roles so here is the solution. In the Account Controller's Register method which is called using [HttpPost], add the following lines in if condition.
using Microsoft.AspNet.Identity.EntityFramework;
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
var roleManager = new RoleManager<IdentityRole>(roleStore);
if(!await roleManager.RoleExistsAsync("YourRoleName"))
await roleManager.CreateAsync(new IdentityRole("YourRoleName"));
await UserManager.AddToRoleAsync(user.Id, "YourRoleName");
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
return RedirectToAction("Index", "Home");
}
This will create first create a role in your database and then add the newly created user to this role.
public static void createUserRole(string roleName)
{
if (!System.Web.Security.Roles.RoleExists(roleName))
{
System.Web.Security.Roles.CreateRole(roleName);
}
}
the method i Use for creating roles is below, assigning them to users in code is also listed. the below code does be in "configuration.cs" in the migrations folder.
string [] roleNames = { "role1", "role2", "role3" };
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
IdentityResult roleResult;
foreach(var roleName in roleNames)
{
if(!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
}
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
UserManager.AddToRole("user", "role1");
UserManager.AddToRole("user", "role2");
context.SaveChanges();