ASP.NET MVC 5 Identity: Extending and Modifying Roles

In a recent article I took a rather long look at extending the ASP.NET 5 Identity model, adding some custom properties to the basic IdentityUser class, and also some basic role-based identity management. We did not discuss modifying, extending, or working directly with Roles, beyond seeding the d

In a recent article I took a rather long look at extending the ASP.NET 5 Identity model, adding some custom properties to the basic IdentityUser class, and also some basic role-based identity management. We did not discuss modifying, extending, or working directly with Roles, beyond seeding the database with some very basic roles with which to manage application access.

Extending the basic ASP.NET IdentityRole class, and working directly with roles from an administrative perspective, requires some careful consideration, and no small amount of work-around code-wise.

As we saw in the previous article, the ASP.NET team made it fairly easy to extend IdentityUser, and also to get some basic Role management happening.

When roles are used to enforce access restrictions within our application, they are basically hard-coded, usually via the [Authorize] attribute. Giving application administrators the ability to add, modify, and delete roles is of limited use if they cannot also modify the access permissions afforded by [Authorize] .

The above notwithstanding, sometimes we might wish to add some properties to our basic roles, such as a brief description.

In this post we will see how we can extend the IdentityRole class, by adding an additional property. We will also add the basic ability to create, edit, and delete roles, and what all is involved with that, despite the fact that any advantage to adding or removing roles is limited by the hard-coded [Authorize] permissions within our application.

If you are using the Identity 2.0 Framework:

This article focuses on customizing and modifying version 1.0 of the ASP.NET Identity framework. If you are using the recently released version 2.0, this code in this article won't work. For more information on working with Identity 2.0, see

Many of the customizations implemented in this article are included "in the box" with the Identity Samples project. I discuss extending and customizing IdentityUser and IdentityRole in Identity 2.0 in a new article,ASP.NET Identity 2.0: Customizing Users and Roles

If you are using the Identity 1.0 Framework:

UPDATE: 2/24/2014 - Thanks to Code Project user Budoray for catching some typos in the code. The EditRoleViewModel and RoleViewModel classes were referenced incorrectly in a number of places, preventing the project from building properly. Fixed!

We have laid the groundwork for what we will be doing in the previous article on Extending Identity Accounts, so we will clone that project and build on top of the work already done. In that project, we:

Created a restricted, internal access MVC site.

Removed extraneous code related to social media account log-ins, and other features we don't need.

Extended the IdentityUser class to include some additional properties, such as first/last names, and email addresses.

Added the ability to assign users to pre-defined roles which govern access to various functionality within our application.

In the original project, I had left all of the Identity-related models in the single file created with the default project template. Before getting started here, I pulled each class out into its own code file. Also, we will be re-building our database and migrations.

After cloning the source, I deleted the existing Migration (not the Migrations folder, just the Migration file within named 201311110510410_Init.cs. We will keep the Migrations/Configuration.cs file as we will be building out on that as we go.

Previously, we were able to define the model class ApplicationUser, which extended the Identity class IdentityUser, run EF Migrations, and with relative ease swap it with IdentityUser in all the areas of our application which previously consumed IdentityUser. Things are not so simple, however, when it comes to extending IdentityRole.

IdentityRole forms a core component in the authorization mechanism for an ASP.NET application. For this reason, we might expect the Identity system to be resistant to casual modification of the IdentityRole class itself, and perhaps equally importantly, the manner in which the rest of the identity system accepts derivatives. So we need to find a way to accomplish what we wish to achieve without compromising the integrity of the Identity mechanism, or those components downstream which may depend upon an instance of IdentityRole to get the job done.

First off, let's take a look at our existing ApplicationDbContext class:

The ApplicationDbContext Class:

In the above, we can see we are inheriting from the class IdentityDbContext<TUser>, which allows us to specify a custom type, so long as that type is derived from IdentityUser. So it appears that the Identity system generally provides a built-in mechanism for extending IdentityUser. Is there a similar path for extending IdentityRole? Turns out there is. Sort of.

As we can see, we have created a derived class and implemented a simple new Description property, along with a new overridden constructor. Next, we need modify our ApplicationDbContext so that, when we run EF Migrations, our database will reflect the proper modeling. Open the ApplicationDbContext class, and add the following override for the OnModelCreating method:

Add These Namespaces to the Top of your Code File:

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Data.Entity;
using System;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using System.Data.Entity.Validation;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;

Then add the following Code to the ApplicationDbContext class:

NOTE: This code is dense and a little messy. Don't work about understanding the details here - just take a high level view and try to grasp the overall idea of how this code is mapping our code objects to database tables. In particular, the manner in which it models the foreign key relationships between tables.

In the above, we are basically telling Entity Framework how to model our inheritance structure into the database. We can, however, tell EF to model our database in such a way that both of our derived classes can also utilize the same tables, and in fact extend them to include our custom fields. Notice how, in the code above, we first tell the modelBuilder to point the IdentityUser class at the table "AspNetUsers", and then also tell it to point ApplicationUser at the same table? We do the same thing later with ApplicationRole.

As you can see, there is actually no getting away from either the IdentityUser or IdentityRole classes - both are used by the Identity system under the covers. We are simply taking advantage of polymorphism such that, at the level of our application, we are able to use our derived classes, while down below, Identity recognizes them as their base implementations. We will see how this affects our application shortly.

Now, however, we can replace IdentityRole with ApplicationRole in most of the rest of our application, and begin using our new Description property. We will begin with our IdentityManager class. I did a little refactoring here while I was at it, so if you are following along, this code will look a little different than what you will find in the original project. Just paste this code in (but make sure your namespaces match!). I also added a few new using's at the top of the code file.

We will also want to update our AddUsersAndRoles() method, which is called by the Seed() method in the Configuration file for EF Migrations. We want to seed the database with Roles which use our new extended properties:

All we really did here was pass an additional argument to the CreateRole() method, such the the seed roles will exhibit our new property. Now, we need to make a few adjustments to our AccountController, View Models, and Views.

In the previous article, we created a SelectRoleEditorViewModel which accepted an instance of IdentityRole as a constructor argument. We need to modify the code here in order to accommodate any new properties we added when we extended IdentityRole. For our example, we just added a single new property, so this is pretty painless:

Recall that, in order to display the list of roles with checkboxes as an HTML form from which we can return the selection choices made by the user, we needed to define an EditorViewModel.cshtml file which corresponded to our EditorViewModel class. In Views/Shared/EditorViewModels open SelectRoleEditorViewModel.cshtml and make the following changes:

To this point, we actually only have one View which displays our Roles - the UserRoles view, where we assign users to one or more Roles within our application. Once again, we really just need to add a table Header element to represent our new Description property: The Updated UserRoles View:

Here is where you may want to think things through a little bit. Consider - the main reason for utilizing Roles within an ASP.NET application is to manage authorization. We do this by hard-coding access permissions to controllers and/or specific methods through the [Authorize] attribute. If we make roles createable/editable/deletable, what can possibly go wrong? Well, a lot. First off, if we deploy our application, then add a role, we really have no way to make use of the new role with respect to the security concerns listed above, without re-compiling and re-deploying our application after adding the new role to whichever methods we hope to secure with it.

The same is true if we change a role name, or worse, delete a role. In fact, an ambitious admin user could lock themselves out of the application altogether! However, there are some cases where we might want to have this functionality anyway. If, for example, you are the developer, and you add some new role permissions via [Authorize] to an existing application, it is more convenient to add the new roles to the database through the front-end than by either manually adding to the database, or re-seeding the application using Migrations. Also, if your application is in production, then re-running migrations really isn't an option anyway. In any case, a number of commentors on my previous post expressed the desire to be able to modify or remove roles, so let's plow ahead!

Once I had everything built out, and I went to use Visual Studio's built-in scaffolding to add a new Roles controller, I ran into some issues. Apparently, by extending IdentityRole the way we have, Entity Framework has some trouble scaffolding up a new controller based on the ApplicationRole model (EF detects some ambiguity between IdentityRole and ApplicationRole). I didn't spend too much time wrestling with this - it was easy enough to code up a simple CRUD controller the old-fashioned way, so that's what I did. Here is my hand-rolled RolesController, ready for action:

In the above, notice that when we go to delete a role, we make a call out to our IdentityManager class to a method named DeleteRole(). Why the complexity, John? Why not just delete the role from the datastore directly? There's a reason for that . . .

Think about it. If you have one or more users assigned to a role, when you delete that role, you want to remove the users from the role first. Otherwise you will run into foreign key issues in your database which will not let you delete the role. So, we need to add a couple important methods to IdentityManager.

Clearly, in order to delete roles, we first need to remove any users from that role first. Then we can delete the role. However, we have to employ a slight hack to do this, because the Identity framework does not actually implement a RemoveRole() method out of the box. Oh, it's there - you can find it if you look hard enough. The RoleStore<IRole> class actually defines a DeleteAsync method. However, it throws a "Not Implemented" exception. Here is how I worked around the issue. Add the following two methods to the IdentityManager class:

First, notice how we pass in a simple RoleId instead of an instance or ApplicationRole? This is because, in order for the Remove(role) method to operate properly, the role passed in as an argument must be from the same ApplicationDbContext instance, which would not be the case if we were to pass one in from our controller. Also notice, before calling _db.Roles.Remove(role) , we retrieve the collection of users who are role members, and remove them. This solves the foreign key relationship problem, and prevents orphan records in the AspNetUserRoles table in our database.

The Views used by the RolesController were created by simply right-clicking on the associated Controller method and selecting "Add View." I'm including it here for completeness, but there is nothing revolutionary going on here. The code for each follows.

Ok, you should now be able to add a new migration, run it, and build out the database. If you are new to EF Migrations, you may want to review Configuring Entity Framework Migrations. In this case, the cloned project already has migrations enabled, so all we need to do is Build, then type into the Package Manager Console:

Add New Migration (Delete the previous Migration file, or choose a new name)

Add-Migration init

Then, if all went well with that,

Update The Database:

If all went well (and I haven't missed anything in this post!) we should be able to run our application, log in, and navigate to the "Users" tab. Then, select the "Roles" link of the single user listed. You should see something similar to this:

The User Roles View:

This was a rather long article to implement some relatively minor functionality. However, we touched on some concepts which may prove helpful if you need just a little more from the new Identity system than is available straight out of the box. Also, I am setting the stage for the next article, where I will look at setting up "Role Groups" to which users may be assigned. In this scenario, we can use the built-in Roles to set pretty granular access permissions within our code, and then assign users to predefined "Groups" of such Role permissions, somewhat mimicking familiar domain permissions.

I do my best when working with membership or Identity to stay within the bounds and mechanisms set up by the ASP.NET team. I am far, far from a security expert (I DID buy a book on it recently, though!), and those people know way more about creating a secure authorization system than I could ever hope to. In the preceding article on extending IdentityUser and adding roles to our application, we stayed well within the bounds of the intended uses of Identity.

In this article, I ventured a little further afield, extending a class which it appears the ASP.NET team did not intend to be easily extended. Further, I implemented a means to create, edit, and delete roles at the application user level. I assume there are reasons such functionality was not built-in out of the box. Most likely for the reasons I discussed previously.

When your security and authorization needs become sufficiently complex, it may be time to examine more robust alternatives to the identity system. After all, the Identity system was designed with the primary objective of securing a public-facing web application, with a limited number of user roles and administrative requirements. Additionally, the NET team has recently released the ASP.NET Identity 2 Preview, which holds additional interesting developments.

That said, near as I can tell we have done nothing here to explicitly compromise the security of our application, or the integrity of the identity system. Our ApplicationRole class, through inheritance and polymorphism, is consumed properly by the internals of the ASP.NET Identity system, while delivering whatever additional properties we required.

If you see where I have something wrong, or missed something while moving the code into this article, please do let me know in the comments, or shoot me an email at the address in the "About the Author" sidebar. If you have suggestions for improving on what you see here, please let me know, or submit a Pull Request on Github. I would love to incorporate any good ideas. Watch for the next article on implementing groups and permissions!

Share

About the Author

My name is John Atten, and my username on many of my online accounts is xivSolutions. I am Fascinated by all things technology and software development. I work mostly with C#, Javascript/Node.js, Various flavors of databases, and anything else I find interesting. I am always looking for new information, and value your feedback (especially where I got something wrong!)

On this surface, this is why you can;t extend IdentityUserRole. Bear in mind, though, that IdentityUSerRole is nothing but a pair of Id's, and a pair of references. If you have extended IdentityUser and IdentityRole per the code above, then what actually ends up in each instance of IdentityUserRole are references to instances of your derived classes. You should be able to cast to type when accessing them like so:

I am on my way out the door to work, so this is off the top of my head, but I banged by head against the wall for some time trying to cajole a derived version of IdentityUserRole to work in the project. In the end, this was the best solution. And, if you think about it, you really don't need to directly access IdentityUserRole much.

what if I want to assign a role to a user which expires after some time? I thought shortest way would be to add DateFrom and DateTo to IdentityUserRole extension class. However I can create new one something similar to Groups in your example project.

The problem I faced was when I ask to remove roles from user (_userManager.RemoveFromRole) it doesn't remove anything and if I use _UM.AddRoleToUser it throws error 'IdenityRole does not exist in current context.

Can you point me to some working example of database first approach for Asp.net Identity? I looked for help on stackoverflow as well and everywhere people are struggling for database first working with asp.net identity. may be next series of your article on asp.net Identity can focus on database first...

My understanding is that the out-of-the-box identity system is basically reliant on Code-First. I believe you would have to pretty much build your solutions up from scratch using the Identity components, and hack your way around the Code-First-Reliant part.

I was able to work with login stuff. However now problem is I have two dbContexts, one is linked with EDMX file and generated by EF. My IdentityDBContext also points to same database. If I use same EF connection I get error 'ApplicationUser' not part of context. If I use new connection pointing to same database I get error (during login) for entities which are part of EF model but not Identity related.

A. Did you follow along and build your project, or did you clone the finished source?
B. Can you post your code/create a repo on github?
C. Can you clarify what you mean by "login with a user via the Users menu item link?"

This type of thing usually turns out to be something silly we missed, either me in the article code, or you while putting it together.

I copied the code from your examples from both parts of this tutorial. I made the following changes. Corrected the references to RoleViewModel and EditRoleViewModel where they were referenced as RolesViewModel and EditRolesViewModel. The other change I made was to use Nickname instead of FirstName and LastName. And, in Configuration.cs, I created my own user with a UserName, Nickname, Email, and set the password.

The project builds and runs fine until I try to log in from the Users link using the UserName and Password for the user that I initialized in the Configuration.cs file. I have no other users defined and I checked to make sure the User is in my database.

Attempting to log in with a bad password will show the warning message, "Invalid username or password." Attempting to log in with the right username and password is when I get the null pointer exception. I am including the error message that is generated. It does the same even when I remove the async functionality. Line count in AccountController.cs is a bit off from your code given that I wrapped the SignInAsync method in a try/catch.

Microsoft.AspNet.Identity.EntityFramework.UserStore`1.<GetRolesAsync>b__1f(IdentityUserRole u)\r\n at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()\r\n at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)\r\n at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)\r\n at Microsoft.AspNet.Identity.EntityFramework.UserStore`1.GetRolesAsync(TUser user)\r\n at Microsoft.AspNet.Identity.UserManager`1.<GetRolesAsync>d__86.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at Microsoft.AspNet.Identity.ClaimsIdentityFactory`1.<CreateAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at Microsoft.AspNet.Identity.AsyncHelper.RunSync[TResult](Func`1 func)\r\n at Microsoft.AspNet.Identity.UserManagerExtensions.CreateIdentity[TUser](UserManager`1 manager, TUser user, String authenticationType)\r\n at Convicts.Guild.Web.Controllers.AccountController.SignInAsync(ApplicationUser user, Boolean isPersistent) in c:\\Projects\\Convicts.Guild\\Convicts.Guild.Web\\Controllers\\AccountController.cs:line 290" string

That code builds, runs, and works from jump (at least, on MY machine lol). It's always possible I made a copy/paste error or something in assembling the code into the article (clearly, as you have already found some!).

I will be interested to know if you figure this out while I am at work. Otherwise, I will try to check into it when I get home this evening.

Here is what I did that fixed the issue. I blew away my database, re-enabled migrations, added an init migration, updated database, and logging in worked as expected. Not that big a deal for me as the data was small and easily recreated.

Awesome. Yeah, I have found it is often more productive to blow away the DB that way. You probably had ended up with some problem foreign keys relationships or something from experimenting. I had a similar issue (different error, so I didn't put it together in my head until just now).