How to add a fixed role (e.g. Admin) to an existing Asp.Net Mvc/Identity 2 site?
In the link
http://bitoftech.net/2015/03/11/asp-net-identity-2-1-roles-based-authorization-authentication-asp-net-web-api/, there are the following code which is exactly what I want to do. However, will the Seed
function be executed since the application? (I already have some code, var lookup1 = new List<L1>{new L1 {...},...}; tableL1.ForEach(l => context.tableL1.AddOrUpdate(p=>p.Title, l)); context.SaveChanges();
, in the Seed
function to seed some lookup tables.). What's the right way to Add a role to an application which is already online?
// internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(AspNetIdentity.WebApi.Infrastructure.ApplicationDbContext context)
{
// This method will be called after migrating to the latest version.
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
var user = new ApplicationUser()
{
UserName = "SuperPowerUser",
Email = "taiseer.joudeh@gmail.com",
EmailConfirmed = true,
FirstName = "Taiseer",
LastName = "Joudeh",
Level = 1,
JoinDate = DateTime.Now.AddYears(-3)
};
manager.Create(user, "MySuperP@ss!");
if (roleManager.Roles.Count() == 0)
{
roleManager.Create(new IdentityRole { Name = "SuperAdmin" });
roleManager.Create(new IdentityRole { Name = "Admin"});
roleManager.Create(new IdentityRole { Name = "User"});
}
var adminUser = manager.FindByName("SuperPowerUser");
manager.AddToRoles(adminUser.Id, new string[] { "SuperAdmin", "Admin" });
}
}