This is a quick tip for those of you working on .NET web applications. In this article I will show you how to pre-populate an ASP.NET MVC web application with initial user accounts and roles. This is helpful in web apps that use their own membership database to store individual user accounts.
I learned this trick from an article I found on the internet years ago. I would love to give credit to the original author, but I don’t keep the link to the article.
Let’s get started.
ASP.NET applications come with four authentication model choices:
- Individual user accounts
- Work and school accounts
- Windows accounts
- No authentication
The individual user accounts model is a great choice when you want to create a SaaS application with its own user accounts database. When you select this approach, the ASP.NET application that you create in Visual Studio is assigned a database with membership tables where you can store user profiles and user roles.
The membership tables are initially empty. You need to seed them with the security roles that you will use in the application so when you run the application for the first time, users that register are assigned to the correct roles.
In many cases, you also want to pre-populate this database with an initial set of users. For example, you might want to create users that will be the app’s administrators, or a few test accounts that you can use to test the app’s features.
In this tutorial I will show you a method that you can follow to seed the membership database with users and roles that will be present the moment the application runs for the first time.
Let’s dive into the code.
Storing Role Names
First, you want to have a place where you will store the names of the different user roles in the application. For simple applications, I generally create a RoleNames Class in the app’s Models folder:
In more complex applications you might want to store the role names in a configuration file. For this example we will define the Administrator, Contributor and Reader role names like so:
public class RoleNames { public const string ROLE_ADMINISTRATOR = "Administrator"; public const string ROLE_CONTRIBUTOR = "Contributor"; public const string ROLE_READER = "Reader"; }
Each role name is a string. You create them as constants so you can refer to them anywhere in the application while maintaining a single place where you can change them if you need to.
The IdentityHelper Class
Next, you will create a Class where you will place a method that will create the initial roles and users in the app’s membership database. I generally name this Class IdentityHelper, and I place it in a Helpers folder that I create in all my ASP.NET apps:
Here’s the Class’s definition:
public class IdentityHelper { }
The SeedIdentities Method
Now let’s define a method that will create the roles and users. Let’s name it SeedIdentities:
public class IdentityHelper { internal static void SeedIdentities(DbContext context) { } }
Creating Roles
Inside SeedIdentities, you will first create the sample roles that we named earlier:
internal static void SeedIdentities(DbContext context) { var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); if (!roleManager.RoleExists(RoleNames.ROLE_ADMINISTRATOR)) { var roleresult = roleManager.Create(new IdentityRole(RoleNames.ROLE_ADMINISTRATOR)); } if (!roleManager.RoleExists(RoleNames.ROLE_CONTRIBUTOR)) { var roleresult = roleManager.Create(new IdentityRole(RoleNames.ROLE_CONTRIBUTOR)); } if (!roleManager.RoleExists(RoleNames.ROLE_READER)) { var roleresult = roleManager.Create(new IdentityRole(RoleNames.ROLE_READER)); } }
The first thing that you do in SeedIdentities is define an instance of the RolesManager Class and an instance of the UserManager Class respectively. These Classes encapsulate the roles and users management methods that we will use in the application.
To create the roles, you first call the RoleManager’s RoleExists method to find out if the role that you want to create already exists in the membership database. If it doesn’t, you create the role by invoking the Create method:
if (!roleManager.RoleExists(RoleNames.ROLE_ADMINISTRATOR)) { var roleresult = roleManager.Create(new IdentityRole(RoleNames.ROLE_ADMINISTRATOR)); }
Creating Users
Now we can move on to creating users. Let’s first define the credentials for the one user that we will create in this example:
string userName = "testuser@emaildomain.com"; string password = "$tr0ngP@ssw0rd!";
Then, create the user and add it to the Administrator role:
ApplicationUser user = userManager.FindByName(userName); if (user == null) { user = new ApplicationUser() { UserName = userName, Email = userName, EmailConfirmed = true }; IdentityResult userResult = userManager.Create(user, password); if (userResult.Succeeded) { var result = userManager.AddToRole(user.Id, RoleNames.ROLE_ADMINISTRATOR); } }
To create the user, you first invoke the UserManager’s FindByName method to find out if a user with the same username already exists in the membership database. If the user isn’t there, you create an instance of the ApplicationUser Class, and pass it to the UserManager’s Create method:
user = new ApplicationUser() { UserName = userName, Email = userName, EmailConfirmed = true }; IdentityResult userResult = userManager.Create(user, password);
Next, assign the user to the Administrator role by calling the UserManager’s AddToRole method:
var result = userManager.AddToRole(user.Id, RoleNames.ROLE_ADMINISTRATOR);
When to Invoke SeedIdentities Method
At this point we’ve written the code that we can use to create the initial roles and users for the app. What’s left is to execute this code, which we can do from the application’s Application_Start method.
As explained by the ASP.NET Application Lifecycle documentation, this method is called when the first resource (such as a page) in an ASP.NET application is requested. The method is called only one time during the life cycle of an application and you can use it to perform startup tasks such as loading data into the cache and initializing static values, which is what we are doing here.
The Application_Start method is defined in the Global.asax file:
You will replace it with the following version:
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ApplicationDbContext context = new ApplicationDbContext(); IdentityHelper.SeedIdentities(context); }
The difference with the out-of-the-box Application_Start method is in the last two lines, where we create an instance of the ApplicationDbContext Class, and invoke the IdentityHelper’s SeedIdentities method.
Summary and Next Steps
This is all it takes to seed the ASP.NET application’s membership database with initial roles and users. Your app’s needs might be different, but the idea is the same – using the Application_Start method, called once during the life cycle of the ASP.NET app, to execute the code that creates the initial roles and users.
Remember to sign up for my newsletter so you can be among the first to know when my next tutorial is available.
Hi Jorge, great tutorial thanks.
One questions, which class do you add the define user credentials to be seeded?