ASP.NET MVC 5 Identity: Implementing Group-Based Permissions Management Part I

Posted on February 19 2014 09:01 PM by jatten in ASP.NET MVC, ASP.Net, C#, CodeProject   ||   Comments (0)

leeds-castle-portcullis-500Over the course of several recent articles, we're examined various ways and means of working with and extending the ASP.NET Identity System. We've covered the basics of configuring the database connections and working with  the EF Code-First approach used by the Identity System, extending the core IdentityUser class to add our own custom properties and behaviors, such as email addresses, First/Last names, and such. While we did that, we also looked at utilizing the basic Role-based account management which comes with ASP.NET Identity out of the box.

In the last post, we figured out how to extend the IdentityRole class, which took a little more doing than was required with IdentityUser.

Image by Shaun Dunmall | Some Rights Reserved

Here, we are going one step further, and building out a more advanced, "permissions management" model on top of the basic Users/Roles paradigm represented by the core ASP.NET Identity System out of the box.

Update: 2/27/2014: According to reader feedback, there will be some modifications required to the code in this article if you are using the newly-released ASP.NET Identity Preview. If you are checking out the Identity preview, be ready to make some adjustments. If you are using the current, stable 1.0 version, this should work quite well. I will post an article detailing the differences in the near future. 

Before we go too much further, it bears mentioning that implementing a complex permissions management system is not a small undertaking. While the model we are about to look at is not overly difficult, managing a large number of granular permissions in the context of a web application could be. You will want to think hard and plan well before you implement something like this in a production site.

With careful up-front planning, and a well-designed permission structure, you should be able to find a middle ground for your site between bloated, complex, and painful enterprise-type solutions such as Active Directory or Windows Authentication and the overly simple Identity management as it comes out of the box.

More on this later. First, some background.

Granular Management of Authorization Permissions - The Principle of Least Privilege

Good security is designed around (among other things) the Principle of Least Privilege. That is, "in a particular abstraction layer of a computing environment, every module (such as a process, a user or a program depending on the subject) must be able to access only the information and resources that are necessary for its legitimate purpose"

As we are well aware by now, the primary way we manage access to different functionality within our ASP.NET MVC application is through the [Authorize] attribute. We decorate specific controller methods with [Authorize] and define which roles can execute the method. For example, we may be building out a site for a business. Among other things, the site will likely contain any number of operational or business domains, such as Site Administration, Human Resources, Sales, Order Processing, and so on.

A hypothetical PayrollController might contain, among others, the following methods:

Methods from a hypothetical Payroll Controller:
[Authorize(Roles = "HrAdmin, CanEnterPayroll")]
[HttpPost]
public ActionResult EnterPayroll(string id)
{
    //  . . . Enter some payroll . . . 
}
  
  
[Authorize(Roles = "HrAdmin, CanEditPayroll, CanProcessPayroll")]
[HttpPost]
public ActionResult EditPayroll(string id)
{
    //  . . . Edit existing payroll entries . . . 
}
  
  
[Authorize(Roles = "HrAdmin, CanProcessPayroll")]
[HttpPost]
public ActionResult ProcessPayroll(string id)
{
    //  . . . Process payroll and cut checks . . . 
}

 

We infer from the above that the grunts who simply enter the payroll information have no business editing work already in the system. On the other hand, there are those in the company who may need to be able to edit existing payroll, which might include the managers of particular employees departments, the HR Manager themselves, and those whose job it is to process the payroll.

The action of actually processing payroll and creating checks for payment is very restricted. Only the HR manager, and those members of the "ProcessPayroll" role are able to do this, and we can assume their number is few.

Lastly, we see that the HrAdmin role has extensive privileges, including all of these functions, and also  presumable is able to act as the administrator within the Human Resources application Domain, assigning these and other domain permissions to the various users within the domain. 

Limitations of Application Authorization Under Identity

Under the current Identity system's out-of-the-box implementation (even with the ways in which we have extended it over these last few articles), We have Users, and Roles. Users are assigned to one or more roles as part of our security setup, and Admins are able to add or remove users from various roles.

Role access to various application functionality is hard-coded into our application via [Authorize], so creating and modifying roles in production is of little value, unless we have implemented some other business reason for it.

Also under the current system, each time we add a new user to the system, we need to assign individual roles specific to the user. This is not a big deal if our site includes (for example) "Admins", "Authors" and "Users." However, for a more complex site, with multiple business domains, and multiple users serving in multiple roles, this could become painful.

When security administration becomes painful, we tend to default to time-saving behavior, such as ignoring the Principle of Least Privilege, and instead granting users broad permissions so we don't have to bother (at least, if we don't have a diligent system admin!).

A Middle of the Road Solution

In this article, we examine one possible manner of extending the Identity model to form a middle-of-the road solution. For applications of moderate complexity, which require a little more granularity in authorization permissions, but which may not warrant moving to a heavy-weight solutions such as Active Directory.

I am proposing the addition of what appear to be authorization Groups to the identity mix. Groups are assigned various combinations of permissions, and Users are assigned to one or more groups.

To do this, we will be creating a slight illusion. We will simply be treating what we currently recognize as Roles as, instead, Permissions. We will then create groups of these "Role-Permissions" and assign users to one or more groups. Behind the scenes, of course, we are still constrained by the essential elements of Identity; Users and Roles. We are also still limited by having to hard-code our "Permissions" into [Authorize] attributes. However, we can define these "Role-Permissions" at a fairly granular level now, because managing assignment of Role Permissions to users will be done by assigning Users to Groups, at which point such a user will assume all of the specific permissions of each particular Group.

Building on Previous Work

I started with the foundation we have built so far, by cloning the project from the last article where we extended our Roles by inheriting from IdentityRole. We didn't do anything earth-shaking in that, but we did get a closer look at how we might override the OnModelCreating() method of ApplicationDbContext and bend EF and the Identity framework to our will, without compromising the underlying security mechanisms created by the ASP.NET team.

You can either do the same, and follow along as we walk through building this out, or you can clone the finished source from this article.

Get the Original Source from Github:
Get the Completed Source for this Article:

As in previous articles, once I have cloned the initial source project, I renamed the solution files, namespaces, directory, and project files, since in my case, I will be pushing this up as a new project, not as new changes to the old.

Next, delete the existing Migrations files (but not the Migrations folder, and not the Configuration.cs file). We will be adding to our Code-First model before we build the database, so we don't need these files anymore.

Now, we're ready to get started.

Adding the Group and ApplicationRoleGroup Models

First, of course, we need our Group class. The Group class will represent a named group of roles, and therefore we consider that the Group class has a collection of roles.  However, since each Group can include zero or many roles, and each role can also belong to zero or many Groups, this will be a many-to-many mapping in our database. Therefore, we first need an intermediate object, ApplicationRoleGroup which maps the foreign keys in the many-to-many relationship.

Add the following classes to the Models folder:

The Application Role Group Model Class:
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
  
  
namespace AspNetGroupBasedPermissions.Models
{
    public class ApplicationRoleGroup
    {
        public virtual string RoleId { get; set; }
        public virtual int GroupId { get; set; }
  
        public virtual ApplicationRole Role { get; set; }
        public virtual Group Group { get; set; }
    }
}

 

Then add the Group class as another new class in Models:

The Group Class:
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
  
namespace AspNetGroupBasedPermissions.Models
{
    public class Group
    {
        public Group() {}
  
  
        public Group(string name) : this()
        {
            this.Roles = new List<ApplicationRoleGroup>();
            this.Name = name;
        }
  
  
        [Key]
        [Required]
        public virtual int Id { get; set; }
  
        public virtual string Name { get; set; }
        public virtual ICollection<ApplicationRoleGroup> Roles { get; set; }
    }
}

 

Next, we need to create a similar many-to-many mapping model for ApplicationUser and Group. Once again, each user can have zero or many groups, and each group can have zero or many users. We already have our ApplicationUser class (although we need to modify it a little), but we need an ApplicationUserGroup class to complete the mapping.

Add the ApplicationUserGroup Model

Add the ApplicationUserGroup class to the Models folder:

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
  
namespace AspNetGroupBasedPermissions.Models
{
    public class ApplicationUserGroup
    {
        [Required]
        public virtual string UserId { get; set; }
        [Required]
        public virtual int GroupId { get; set; }
  
        public virtual ApplicationUser User { get; set; }
        public virtual Group Group { get; set; }
    }
}

 

Next, we need to add a Groups Property to ApplicationUser, in such a manner that Entity Framework will understand and be able to use it to populate the groups when the property is accessed. This means we need to add a virtual property which returns a instance of ICollection<ApplicationUserGroup> when the property is accessed.

Modify the existing ApplicationUser class as follows:

Modified ApplicationUser Class:
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
  
namespace AspNetGroupBasedPermissions.Models
{
    public class ApplicationUser : IdentityUser
    {
        public ApplicationUser()
            : base()
        {
            this.Groups = new HashSet<ApplicationUserGroup>();
        }
  
        [Required]
        public string FirstName { get; set; }
  
        [Required]
        public string LastName { get; set; }
  
        [Required]
        public string Email { get; set; }
  
        public virtual ICollection<ApplicationUserGroup> Groups { get; set; }
    }
}

 

Update ApplicationDbContext to Reflect the New Model

Now that we have extended our model somewhat, we need to update the OnModelCreating method of ApplicationDbContext so that EF can properly model our database, and work with our objects.

** This whole method becomes a little messy and cluttered, but a discerning read of the code reveals the gist of what is happening here. Don't worry too much about understanding the details of this code - just try to get a general picture of how it is mapping model entities to database tables. **

Update the OnModelCreating() method of ApplicationDbContext as follows:

Modified OnModelCreating Method for ApplicationDbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    if (modelBuilder == null)
    {
        throw new ArgumentNullException("modelBuilder");
    }
    // Keep this:
    modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
    // Change TUser to ApplicationUser everywhere else - IdentityUser 
    // and ApplicationUser essentially 'share' the AspNetUsers Table in the database:
    EntityTypeConfiguration<ApplicationUser> table = 
        modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
    table.Property((ApplicationUser u) => u.UserName).IsRequired();
    // EF won't let us swap out IdentityUserRole for ApplicationUserRole here:
    modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
    modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) => 
        new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");
    // Add the group stuff here:
    modelBuilder.Entity<ApplicationUser>().HasMany<ApplicationUserGroup>((ApplicationUser u) => u.Groups);
    modelBuilder.Entity<ApplicationUserGroup>().HasKey((ApplicationUserGroup r) => 
        new { UserId = r.UserId, GroupId = r.GroupId }).ToTable("ApplicationUserGroups");
    // And here:
    modelBuilder.Entity<Group>().HasMany<ApplicationRoleGroup>((Group g) => g.Roles);
    modelBuilder.Entity<ApplicationRoleGroup>().HasKey((ApplicationRoleGroup gr) => 
        new { RoleId = gr.RoleId, GroupId = gr.GroupId }).ToTable("ApplicationRoleGroups");
    // And Here:
    EntityTypeConfiguration<Group> groupsConfig = modelBuilder.Entity<Group>().ToTable("Groups");
    groupsConfig.Property((Group r) => r.Name).IsRequired();
    // Leave this alone:
    EntityTypeConfiguration<IdentityUserLogin> entityTypeConfiguration = 
        modelBuilder.Entity<IdentityUserLogin>().HasKey((IdentityUserLogin l) => 
            new { UserId = l.UserId, LoginProvider = l.LoginProvider, ProviderKey = 
                l.ProviderKey }).ToTable("AspNetUserLogins");
    entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
    EntityTypeConfiguration<IdentityUserClaim> table1 = 
        modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
    table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);
    // Add this, so that IdentityRole can share a table with ApplicationRole:
    modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
    // Change these from IdentityRole to ApplicationRole:
    EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 = 
        modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
    entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
}

 

Next, we need to explicitly add a Groups property on ApplicationDbContext. Once again, this needs to be a virtual property, but in this case the return type is ICollection<Group>:

Add the Groups Property to ApplicationDbcontext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    // Add an instance IDbSet using the 'new' keyword:
    new public virtual IDbSet<ApplicationRole> Roles { get; set; }
  
    // ADD THIS:
    public virtual IDbSet<Group> Groups { get; set; }
  
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
  
  
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Code we just added above is here . .  .
    }
  
    // Etc . . .
}

 

Add Group Management Items to Identity Manager

Now, let's add some code to help us manage the various functionality we need related to Groups, and management of users and Roles ("permissions") related to Groups. Look over the methods below carefully to understand just what is going on most of the time, as several of the actions one might take upon a group have potential consequences across the security spectrum.

For example, when we delete a group, we need to also:

  • Remove all the users from the group. Remember, there is a foreign key relationship here with an intermediate or "relations table" - related records need to be removed first, or we will generally get a key constraint error.
  • Remove all the roles from that group. Remember, there is a foreign key relationship here with an intermediate or "relations table" - related records need to be removed first, or we will generally get a key constraint error.
  • Remove the roles from each user, except when that user has the same role resulting from membership in another group (this was a pain to think through!).

Likewise, when we add a Role ("Permission") to a group, we need to update all of the users in that group to reflect the added permission.

Add the following methods to the bottom of the existing IdentityManager class:

Add Group Methods to Identity Manager Class:
public void CreateGroup(string groupName)
{
    if (this.GroupNameExists(groupName))
    {
        throw new System.Exception("A group by that name already exists in the database. Please choose another name.");
    }
  
    var newGroup = new Group(groupName);
    _db.Groups.Add(newGroup);
    _db.SaveChanges();
}
  
  
public bool GroupNameExists(string groupName)
{
    var g = _db.Groups.Where(gr => gr.Name == groupName);
    if (g.Count() > 0)
    {
        return true;
    }
    return false;
}
  
  
public void ClearUserGroups(string userId)
{
    this.ClearUserRoles(userId);
    var user = _db.Users.Find(userId);
    user.Groups.Clear();
    _db.SaveChanges();
}
  
  
public void AddUserToGroup(string userId, int GroupId)
{
    var group = _db.Groups.Find(GroupId);
    var user = _db.Users.Find(userId);
  
    var userGroup = new ApplicationUserGroup()
    {
        Group = group,
        GroupId = group.Id,
        User = user,
        UserId = user.Id
    };
  
    foreach (var role in group.Roles)
    {
        _userManager.AddToRole(userId, role.Role.Name);
    }
    user.Groups.Add(userGroup);
    _db.SaveChanges();
}
  
  
public void ClearGroupRoles(int groupId)
{
    var group = _db.Groups.Find(groupId);
    var groupUsers = _db.Users.Where(u => u.Groups.Any(g => g.GroupId == group.Id));
  
    foreach (var role in group.Roles)
    {
        var currentRoleId = role.RoleId;
        foreach (var user in groupUsers)
        {
            // Is the user a member of any other groups with this role?
            var groupsWithRole = user.Groups
                .Where(g => g.Group.Roles
                    .Any(r => r.RoleId == currentRoleId)).Count();
            // This will be 1 if the current group is the only one:
            if (groupsWithRole == 1)
            {
                this.RemoveFromRole(user.Id, role.Role.Name);
            }
        }
    }
    group.Roles.Clear();
    _db.SaveChanges();
}
  
  
public void AddRoleToGroup(int groupId, string roleName)
{
    var group = _db.Groups.Find(groupId);
    var role = _db.Roles.First(r => r.Name == roleName);
    var newgroupRole = new ApplicationRoleGroup()
    {
        GroupId = group.Id,
        Group = group,
        RoleId = role.Id,
        Role = (ApplicationRole)role
    };
  
    group.Roles.Add(newgroupRole);
    _db.SaveChanges();
  
    // Add all of the users in this group to the new role:
    var groupUsers = _db.Users.Where(u => u.Groups.Any(g => g.GroupId == group.Id));
    foreach (var user in groupUsers)
    {
        if(!(_userManager.IsInRole(user.Id, roleName)))
        {
            this.AddUserToRole(user.Id, role.Name);
        }
    }
}
  
  
public void DeleteGroup(int groupId)
{
    var group = _db.Groups.Find(groupId);
  
    // Clear the roles from the group:
    this.ClearGroupRoles(groupId);
    _db.Groups.Remove(group);
    _db.SaveChanges();
}

 

We now have the core code needed to manage the relationships between Users, Groups, and Roles ("Permissions") in the back end. Now we need to set up our Migrations Configuration file to properly seed our database when we run EF Migrations.

Update the Migrations Configuration File to Seed the Database

Most of the basic model stuff is now in place such that we can run EF Migrations and build out our modified database. Before we do that, though, we want to update our Migrations Configuration class so that we seed our database with the minimal required data to function. Remember, our site is closed to "public" registration. Therefore, at the very least we need to seed it with an initial admin-level user, just like before.

What is NOT like before is that we have changed the manner in which roles are assigned and managed. Going forward, we need to seed our initial user, along with one or more initial Groups, and seed at least one of those groups with sufficient admin permissions that our initial user can take it from there.

There are many ways this code could be written. Further, depending upon your application requirements, how the database is seeded may become an extensive exercise in planning (remember that bit about how a more complex authorization model requires more and more up-front planning?).

Here, we are going to update our Configuration class with a few new methods. We will add an initial user, a handful of potentially useful Groups, and some roles relevant to managing security and authorization.

Updated Migrations Configuration File:
internal sealed class Configuration 
    : DbMigrationsConfiguration<ApplicationDbContext>
{
    IdentityManager _idManager = new IdentityManager();
    ApplicationDbContext _db = new ApplicationDbContext();
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
    }
  
  
    protected override void Seed(ApplicationDbContext context)
    {
        this.AddGroups();
        this.AddRoles();
        this.AddUsers();
        this.AddRolesToGroups();
        this.AddUsersToGroups();
    }
   
    string[] _initialGroupNames = 
        new string[] { "SuperAdmins", "GroupAdmins", "UserAdmins", "Users" };
    public void AddGroups()
    {
        foreach (var groupName in _initialGroupNames)
        {
            _idManager.CreateGroup(groupName);
        }
    }
  
  
    void AddRoles()
    {
        // Some example initial roles. These COULD BE much more granular:
        _idManager.CreateRole("Admin", "Global Access");
        _idManager.CreateRole("CanEditUser", "Add, modify, and delete Users");
        _idManager.CreateRole("CanEditGroup", "Add, modify, and delete Groups");
        _idManager.CreateRole("CanEditRole", "Add, modify, and delete roles");
        _idManager.CreateRole("User", "Restricted to business domain activity");
    }
  
  
    string[] _superAdminRoleNames = 
        new string[] { "Admin", "CanEditUser", "CanEditGroup", "CanEditRole", "User" };
    string[] _groupAdminRoleNames =
        new string[] { "CanEditUser", "CanEditGroup", "User" };
    string[] _userAdminRoleNames =
        new string[] { "CanEditUser", "User" };
    string[] _userRoleNames =
        new string[] { "User" };
    void AddRolesToGroups()
    {
        // Add the Super-Admin Roles to the Super-Admin Group:
        var allGroups = _db.Groups;
        var superAdmins = allGroups.First(g => g.Name == "SuperAdmins");
        foreach (string name in _superAdminRoleNames)
        {
            _idManager.AddRoleToGroup(superAdmins.Id, name);
        }
  
        // Add the Group-Admin Roles to the Group-Admin Group:
        var groupAdmins = _db.Groups.First(g => g.Name == "GroupAdmins");
        foreach (string name in _groupAdminRoleNames)
        {
            _idManager.AddRoleToGroup(groupAdmins.Id, name);
        }
  
        // Add the User-Admin Roles to the User-Admin Group:
        var userAdmins = _db.Groups.First(g => g.Name == "UserAdmins");
        foreach (string name in _userAdminRoleNames)
        {
            _idManager.AddRoleToGroup(userAdmins.Id, name);
        }
  
        // Add the User Roles to the Users Group:
        var users = _db.Groups.First(g => g.Name == "Users");
        foreach (string name in _userRoleNames)
        {
            _idManager.AddRoleToGroup(users.Id, name);
        }
    }
  
  
    // Change these to your own:
    string _initialUserName = "jatten";
    string _InitialUserFirstName = "John";
    string _initialUserLastName = "Atten";
    string _initialUserEmail = "jatten@typecastexception.com";
    void AddUsers()
    {
        var newUser = new ApplicationUser()
        {
            UserName = _initialUserName,
            FirstName = _InitialUserFirstName,
            LastName = _initialUserLastName,
            Email = _initialUserEmail
        };
  
        // Be careful here - you  will need to use a password which will 
        // be valid under the password rules for the application, 
        // or the process will abort:
        _idManager.CreateUser(newUser, "Password1");
    }
  
  
    // Configure the initial Super-Admin user:
    void AddUsersToGroups()
    {
        var user = _db.Users.First(u => u.UserName == _initialUserName);
        var allGroups = _db.Groups;
        foreach (var group in allGroups)
        {
            _idManager.AddUserToGroup(user.Id, group.Id);
        }
    }
}

 

As you can see in the above, I have (rather arbitrarily) decided to set up some initial groups and roles related to the Users/Groups/Roles domain. If we already knew the domain structure of the rest of our application, we might want to include additional roles ("Permissions") as part of our Configuration, since roles need to be hard-coded into our controllers using the [Authorize] attribute. The earlier we can determine the role structure for our application security model, the better. You will want to strike a balance between granularity and manageability here, though.

For the moment, we have a sufficient starting point, and we are ready to run EF Migrations and see if our database is built successfully.

Run Migrations and Build Out the Database

As mentioned previously, as I did this, I deleted the previous Migration files, but left the Migrations folder intact, with the (now modified Configuration.cs file). Therefore, in order to perform the migration, I simply type the following into the Package Manager Console:

Add New Migration:
PM> Add-Migration init

 

This scaffolds up a new migration. Next:

Build Out the Database:
PM> Update-Database

 

If everything went well, we should be able to open our database in the Visual Studio Server Explorer and see how we did. You should see something like this:

The Database in VS Server Explorer:

vs-server-explorer-database-view

Looks like everything went ok!

Next: Controllers, ViewModels, and Views

This article became long enough that I decided to break it into two parts. In this post, we figured out how to model our Users, Groups, and Roles ("Permissions") in our application, and by extension, in our database via EF Code-First and Migrations.

Next, we will start pulling all this together into the business end of our application

Next:  Part II - Controllers, ViewModels, and Views --->

 

Additional Resources and Items of Interest

 

Posted on February 19 2014 09:01 PM by jatten     

Comments (0)

ASP.NET MVC 5 Identity: Extending and Modifying Roles

Posted on February 13 2014 09:17 PM by jatten in ASP.NET MVC, ASP.Net, C#, CodeProject   ||   Comments (8)

 

security-cam-by-hay-kranenIn 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.

Image by Hay Kranen | Some Rights Reserved

There are two reasons this is so:

  • 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.

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 "ini 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:

Keep Reading!

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.

In the next post, ASP.NET MVC 5 Identity: Implementing Group-Based Permissions Management,  look at working around the limitations of the Role/[Authorize] model to create a more finely-grained role-based access control system.

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!

In an upcoming post we will look at working around the limitations of the Role/[Authorize] model to create a more finely-grained role-based access control system.

Getting Started - Building on Previous Work

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.

Clone the Source

You can clone the original project and follow along, or you can grab the finished project from my Github repo. To get the original project and build along with this article, clone the source from:

If you want to check out the finished project, clone the source from:

First, a Little Refactoring

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.

If you are following along, note that I also renamed the project and solution, namespaces, and such, as I am going to push this project up to Github separately from the original.

There is plenty of room for additional cleanup in this project, but for now, it will do. Let's get started.

Getting Started

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:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
}

 

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.

Extending the Identity Role Class

First, of course, we need to create our derived class, ApplicationRole. Add the following class to the Models folder:

The Application Role Class:
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace AspNetExtendingIdentityRoles.Models
{
    public class ApplicationRole : IdentityRole
    {
        public ApplicationRole() : base() { }
        public ApplicationRole(string name, string description) : base(name)
        {
            this.Description = description;
        }
        public virtual string Description { get; set; }
    }
}

 

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:

Overriding the OnModelCreating method:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    if (modelBuilder == null)
    {
        throw new ArgumentNullException("modelBuilder");
    }
  
    // Keep this:
    modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
  
    // Change TUser to ApplicationUser everywhere else - 
    // IdentityUser and ApplicationUser essentially 'share' the AspNetUsers Table in the database:
    EntityTypeConfiguration<ApplicationUser> table = 
        modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
  
    table.Property((ApplicationUser u) => u.UserName).IsRequired();
  
    // EF won't let us swap out IdentityUserRole for ApplicationUserRole here:
    modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
    modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) => 
        new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");
  
    // Leave this alone:
    EntityTypeConfiguration<IdentityUserLogin> entityTypeConfiguration = 
        modelBuilder.Entity<IdentityUserLogin>().HasKey((IdentityUserLogin l) => 
            new { UserId = l.UserId, LoginProvider = l.LoginProvider, ProviderKey 
            	= l.ProviderKey }).ToTable("AspNetUserLogins");
  
    entityTypeConfiguration.HasRequired<IdentityUser>((IdentityUserLogin u) => u.User);
    EntityTypeConfiguration<IdentityUserClaim> table1 = 
    	modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
  
    table1.HasRequired<IdentityUser>((IdentityUserClaim u) => u.User);
  
    // Add this, so that IdentityRole can share a table with ApplicationRole:
    modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
  
    // Change these from IdentityRole to ApplicationRole:
    EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 = 
    	modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
  
    entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
}

          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.

          Update the Identity Manager Class

          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.

          Modified Identity Manager Class:
          public class IdentityManager
          
          {
          
              // Swap ApplicationRole for IdentityRole:
          
              RoleManager<ApplicationRole> _roleManager = new RoleManager<ApplicationRole>(
          
                  new RoleStore<ApplicationRole>(new ApplicationDbContext()));
          
            
          
              UserManager<ApplicationUser> _userManager = new UserManager<ApplicationUser>(
          
                  new UserStore<ApplicationUser>(new ApplicationDbContext()));
          
            
          
              ApplicationDbContext _db = new ApplicationDbContext();
          
            
          
            
          
              public bool RoleExists(string name)
          
              {
          
                  return _roleManager.RoleExists(name);
          
              }
          
            
          
            
          
              public bool CreateRole(string name, string description = "")
          
              {
          
                  // Swap ApplicationRole for IdentityRole:
          
                  var idResult = _roleManager.Create(new ApplicationRole(name, description));
          
                  return idResult.Succeeded;
          
              }
          
            
          
            
          
              public bool CreateUser(ApplicationUser user, string password)
          
              {
          
                  var idResult = _userManager.Create(user, password);
          
                  return idResult.Succeeded;
          
              }
          
            
          
            
          
              public bool AddUserToRole(string userId, string roleName)
          
              {
          
                  var idResult = _userManager.AddToRole(userId, roleName);
          
                  return idResult.Succeeded;
          
              }
          
            
          
            
          
              public void ClearUserRoles(string userId)
          
              {
          
                  var user = _userManager.FindById(userId);
          
                  var currentRoles = new List<IdentityUserRole>();
          
            
          
                  currentRoles.AddRange(user.Roles);
          
                  foreach (var role in currentRoles)
          
                  {
          
                      _userManager.RemoveFromRole(userId, role.Role.Name);
          
                  }
          
              }
          
          }

           

          Update the Add Users and Roles Method in Migrations Configuration

          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:

          The Updated Add Users and Groups Method:
          bool AddUserAndRoles()
          
          {
          
              bool success = false;
          
              var idManager = new IdentityManager();
          
              // Add the Description as an argument:
          
              success = idManager.CreateRole("Admin", "Global Access");
          
              if (!success == true) return success;
          
              // Add the Description as an argument:
          
              success = idManager.CreateRole("CanEdit", "Edit existing records");
          
              if (!success == true) return success;
          
              // Add the Description as an argument:
          
              success = idManager.CreateRole("User", "Restricted to business domain activity");
          
              if (!success) return success;
          
              // While you're at it, change this to your own log-in:
          
              var newUser = new ApplicationUser()
          
              {
          
                  UserName = "jatten",
          
                  FirstName = "John",
          
                  LastName = "Atten",
          
                  Email = "jatten@typecastexception.com"
          
              };
          
              // Be careful here - you  will need to use a password which will 
          
              // be valid under the password rules for the application, 
          
              // or the process will abort:
          
              success = idManager.CreateUser(newUser, "Password1");
          
              if (!success) return success;
          
              success = idManager.AddUserToRole(newUser.Id, "Admin");
          
              if (!success) return success;
          
              success = idManager.AddUserToRole(newUser.Id, "CanEdit");
          
              if (!success) return success;
          
              success = idManager.AddUserToRole(newUser.Id, "User");
          
              if (!success) return success;
          
              return success;
          
          }

           

          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 Account Controller, View Models, and Views.

          Update the Select Role Editor View Model

          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:

          The Modified SelectRoleEditorViewModel:
          public class SelectRoleEditorViewModel
          
          {
          
              public SelectRoleEditorViewModel() { }
          
            
          
              // Update this to accept an argument of type ApplicationRole:
          
              public SelectRoleEditorViewModel(ApplicationRole role)
          
              {
          
                  this.RoleName = role.Name;
          
            
          
                  // Assign the new Descrption property:
          
                  this.Description = role.Description;
          
              }
          
            
          
            
          
              public bool Selected { get; set; }
          
            
          
              [Required]
          
              public string RoleName { get; set; }
          
            
          
              // Add the new Description property:
          
              public string Description { get; set; }
          
          }

           

          Update the Corresponding Editor View Model

          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:

          The Modified SelectRoleEditorViewModel:
          @model AspNetExtendingIdentityRoles.Models.SelectRoleEditorViewModel
          
          @Html.HiddenFor(model => model.RoleName)
          
          <tr>
          
              <td style="text-align:center">
          
                  @Html.CheckBoxFor(model => model.Selected)
          
              </td>
          
              <td style="padding-right:20px">
          
                  @Html.DisplayFor(model => model.RoleName)
          
              </td>
          
              <td style="padding-right:20px">
          
                  @Html.DisplayFor(model => model.Description)
          
              </td>
          
          </tr>

          Again, all we needed to do in the above was add a table data element for the new property.

          Update the User Roles View

          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:

          @model AspNetExtendingIdentityRoles.Models.SelectUserRolesViewModel
          
            
          
          @{
          
              ViewBag.Title = "User Roles";
          
          }
          
          <h2>Roles for user @Html.DisplayFor(model => model.UserName)</h2>
          
          <hr />
          
          @using (Html.BeginForm("UserRoles", "Account", FormMethod.Post, new { encType = "multipart/form-data", name = "myform" }))
          
          {
          
              @Html.AntiForgeryToken()
          
            
          
              <div class="form-horizontal">
          
                  @Html.ValidationSummary(true)
          
                  <div class="form-group">
          
                      <div class="col-md-10">
          
                          @Html.HiddenFor(model => model.UserName)
          
                      </div>
          
                  </div>
          
            
          
                  <h4>Select Role Assignments</h4>
          
                  <br />
          
                  <hr />
          
            
          
                  <table>
          
                      <tr>
          
                          <th>
          
                              Select
          
                          </th>
          
                          <th>
          
                              Role
          
                          </th>
          
                          <th>
          
                              Description
          
                          </th>
          
                      </tr>
          
            
          
                      @Html.EditorFor(model => model.Roles)
          
                  </table>
          
                  <br />
          
                  <hr />
          
            
          
                  <div class="form-group">
          
                      <div class="col-md-offset-2 col-md-10">
          
                          <input type="submit" value="Save" class="btn btn-default" />
          
                      </div>
          
                  </div>
          
              </div>
          
          }
          
            
          
          <div>
          
              @Html.ActionLink("Back to List", "Index")
          
          </div>

           

          Do We Really Want to Edit Roles?

          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, the 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!

          Why Not? Adding the Roles Controller

          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 yup a simple CRUD controller the old-fashioned way, so that's what I did.

          Here is my hand-rolled RolesController, ready for action:

          The Roles Controller:
          using AspNetExtendingIdentityRoles.Models;
          
          using System.Collections.Generic;
          
          using System.Data.Entity;
          
          using System.Linq;
          
          using System.Net;
          
          using System.Web.Mvc;
          
            
          
          namespace AspNetExtendingIdentityRoles.Controllers
          
          {
          
              public class RolesController : Controller
          
              {
          
                  private ApplicationDbContext _db = new ApplicationDbContext();
          
            
          
                  public ActionResult Index()
          
                  {
          
                      var rolesList = new List<RoleViewModel>();
          
                      foreach(var role in _db.Roles)
          
                      {
          
                          var roleModel = new RoleViewModel(role);
          
                          rolesList.Add(roleModel);
          
                      }
          
                      return View(rolesList);
          
                  }
          
            
          
            
          
                  [Authorize(Roles = "Admin")]
          
                  public ActionResult Create(string message = "")
          
                  {
          
                      ViewBag.Message = message;
          
                      return View();
          
                  }
          
            
          
            
          
                  [HttpPost]
          
                  [Authorize(Roles = "Admin")]
          
                  public ActionResult Create([Bind(Include = 
          
                      "RoleName,Description")]RoleViewModel model)
          
                  {
          
                      string message = "That role name has already been used";
          
                      if (ModelState.IsValid)
          
                      {
          
                          var role = new ApplicationRole(model.RoleName, model.Description);
          
                          var idManager = new IdentityManager();
          
            
          
                          if(idManager.RoleExists(model.RoleName))
          
                          {
          
                              return View(message);
          
                          }
          
                          else
          
                          {
          
                              idManager.CreateRole(model.RoleName, model.Description);
          
                              return RedirectToAction("Index", "Account");
          
                          }
          
                      }
          
                      return View();
          
                  }
          
            
          
            
          
                  [Authorize(Roles = "Admin")]
          
                  public ActionResult Edit(string id)
          
                  {
          
                      // It's actually the Role.Name tucked into the id param:
          
                      var role = _db.Roles.First(r => r.Name == id);
          
                      var roleModel = new EditRoleViewModel(role);
          
                      return View(roleModel);
          
                  }
          
            
          
            
          
                  [HttpPost]
          
                  [Authorize(Roles = "Admin")]
          
                  public ActionResult Edit([Bind(Include = 
          
                      "RoleName,OriginalRoleName,Description")] EditRoleViewModel model)
          
                  {
          
                      if (ModelState.IsValid)
          
                      {
          
                          var role = _db.Roles.First(r => r.Name == model.OriginalRoleName);
          
                          role.Name = model.RoleName;
          
                          role.Description = model.Description;
          
                          _db.Entry(role).State = EntityState.Modified;
          
                          _db.SaveChanges();
          
                          return RedirectToAction("Index");
          
                      }
          
                      return View(model);
          
                  }
          
            
          
            
          
                  [Authorize(Roles = "Admin")]
          
                  public ActionResult Delete(string id)
          
                  {
          
                      if (id == null)
          
                      {
          
                          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
          
                      }
          
                      var role = _db.Roles.First(r => r.Name == id);
          
                      var model = new RoleViewModel(role);
          
                      if (role == null)
          
                      {
          
                          return HttpNotFound();
          
                      }
          
                      return View(model);
          
                  }
          
            
          
            
          
                  [Authorize(Roles = "Admin")]
          
                  [HttpPost, ActionName("Delete")]
          
                  public ActionResult DeleteConfirmed(string id)
          
                  {
          
                      var role = _db.Roles.First(r => r.Name == id);
          
                      var idManager = new IdentityManager();
          
                      idManager.DeleteRole(role.Id);
          
                      return RedirectToAction("Index");
          
                  }
          
              }
          
          }

           

          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 . . .

          About Deleting Roles

          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.

          Adding a Delete Role Method to Identity Manager

          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:

          Adding DeleteRole and RemoveFromRole Methods to Identity Manager Class:
          public void RemoveFromRole(string userId, string roleName)
          
          {
          
              _userManager.RemoveFromRole(userId, roleName);
          
          }
          
            
          
            
          
          public void DeleteRole(string roleId)
          
          {
          
              var roleUsers = _db.Users.Where(u => u.Roles.Any(r => r.RoleId == roleId));
          
              var role = _db.Roles.Find(roleId);
          
            
          
              foreach (var user in roleUsers)
          
              {
          
                  this.RemoveFromRole(user.Id, role.Name);
          
              }
          
              _db.Roles.Remove(role);
          
              _db.SaveChanges();
          
          }

           

          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.

          ViewModels and Views for the Roles Controller

          Notice in our controller, we make use of two new View Models, the RoleViewModel, and the EditRoleViewModel. I went ahead and added these to the AccountViewModels.cs file. The code is as follows:

          The RoleViewModel and EditRoleViewModel Classes:
          public class RoleViewModel
          
          {
          
              public string RoleName { get; set; }
          
              public string Description { get; set; }
          
            
          
              public RoleViewModel() { }
          
              public RoleViewModel(ApplicationRole role)
          
              {
          
                  this.RoleName = role.Name;
          
                  this.Description = role.Description;
          
              }
          
          }
          
            
          
            
          
          public class EditRoleViewModel
          
          {
          
              public string OriginalRoleName { get; set; }
          
              public string RoleName { get; set; }
          
              public string Description { get; set; }
          
            
          
              public EditRoleViewModel() { }
          
              public EditRoleViewModel(ApplicationRole role)
          
              {
          
                  this.OriginalRoleName = role.Name;
          
                  this.RoleName = role.Name;
          
                  this.Description = role.Description;
          
              }
          
          }

           

          Views Used by the Role Controller

          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.

          The Index Role View

          Displays a list of the Roles, along with Action Links to Edit or Delete.

          Code for the Create Role View:
          @model IEnumerable<AspNetExtendingIdentityRoles.Models.RoleViewModel>
          
            
          
          @{
          
              ViewBag.Title = "Application Roles";
          
          }
          
            
          
          <h2>Application Roles</h2>
          
            
          
          <p>
          
              @Html.ActionLink("Create New", "Create")
          
          </p>
          
          <table class="table">
          
              <tr>
          
                  <th>
          
                      @Html.DisplayNameFor(model => model.RoleName)
          
                  </th>
          
                  <th>
          
                      @Html.DisplayNameFor(model => model.Description)
          
                  </th>
          
                  <th></th>
          
              </tr>
          
            
          
          @foreach (var item in Model) {
          
              <tr>
          
                  <td>
          
                      @Html.DisplayFor(modelItem => item.RoleName)
          
                  </td>
          
                  <td>
          
                      @Html.DisplayFor(modelItem => item.Description)
          
                  </td>
          
                  <td>
          
                      @Html.ActionLink("Edit", "Edit", new { id = item.RoleName }) |
          
                      @Html.ActionLink("Delete", "Delete", new { id = item.RoleName })
          
                  </td>
          
              </tr>
          
          }
          
            
          
          </table>

           

          The Create Role View

          Obviously, affords creation of new Roles.

          Code for the Create Role View:
          @model AspNetExtendingIdentityRoles.Models.RoleViewModel
          
            
          
          @{
          
              ViewBag.Title = "Create";
          
          }
          
            
          
          <h2>Create Role</h2>
          
            
          
            
          
          @using (Html.BeginForm()) 
          
          {
          
              @Html.AntiForgeryToken()
          
                
          
              <div class="form-horizontal">
          
                  <h4>RoleViewModel</h4>
          
                  <hr />
          
                  @Html.ValidationSummary(true)
          
            
          
                  @if(ViewBag.Message != "")
          
                  {
          
                      <p style="color: red">ViewBag.Message</p>
          
                  }
          
                  <div class="form-group">
          
                      @Html.LabelFor(model => model.RoleName, 
          
                      	new { @class = "control-label col-md-2" })
          
                      <div class="col-md-10">
          
                          @Html.EditorFor(model => model.RoleName)
          
                          @Html.ValidationMessageFor(model => model.RoleName)
          
                      </div>
          
                  </div>
          
            
          
                  <div class="form-group">
          
                      @Html.LabelFor(model => model.Description, 
          
                      	new { @class = "control-label col-md-2" })
          
                      <div class="col-md-10">
          
                          @Html.EditorFor(model => model.Description)
          
                          @Html.ValidationMessageFor(model => model.Description)
          
                      </div>
          
                  </div>
          
            
          
                  <div class="form-group">
          
                      <div class="col-md-offset-2 col-md-10">
          
                          <input type="submit" value="Create" class="btn btn-default" />
          
                      </div>
          
                  </div>
          
              </div>
          
          }
          
            
          
          <div>
          
              @Html.ActionLink("Back to List", "Index")
          
          </div>
          
            
          
          @section Scripts {
          
              @Scripts.Render("~/bundles/jqueryval")
          
          }

           

          The Edit Roles View

          For, um, editing Roles . ..

          Code for the Edit Roles View:
          @model AspNetExtendingIdentityRoles.Models.EditRoleViewModel
          
            
          
          @{
          
              ViewBag.Title = "Edit";
          
          }
          
            
          
          <h2>Edit</h2>
          
            
          
            
          
          @using (Html.BeginForm())
          
          {
          
              @Html.AntiForgeryToken()
          
                
          
              <div class="form-horizontal">
          
                  <h4>EditRoleViewModel</h4>
          
                  <hr />
          
                  @Html.ValidationSummary(true)
          
            
          
                  @*Hide the original name away for later:*@
          
                  @Html.HiddenFor(model => model.OriginalRoleName)
          
            
          
                  <div class="form-group">
          
                      @Html.LabelFor(model => model.RoleName, 
          
                      	new { @class = "control-label col-md-2" })
          
                      <div class="col-md-10">
          
                          @Html.EditorFor(model => model.RoleName)
          
                          @Html.ValidationMessageFor(model => model.RoleName)
          
                      </div>
          
                  </div>
          
            
          
                  <div class="form-group">
          
                      @Html.LabelFor(model => model.Description, 
          
                      	new { @class = "control-label col-md-2" })
          
                      <div class="col-md-10">
          
                          @Html.EditorFor(model => model.Description)
          
                          @Html.ValidationMessageFor(model => model.Description)
          
                      </div>
          
                  </div>
          
            
          
                  <div class="form-group">
          
                      <div class="col-md-offset-2 col-md-10">
          
                          <input type="submit" value="Save" class="btn btn-default" />
          
                      </div>
          
                  </div>
          
              </div>
          
          }
          
            
          
          <div>
          
              @Html.ActionLink("Back to List", "Index")
          
          </div>
          
            
          
          @section Scripts {
          
              @Scripts.Render("~/bundles/jqueryval")
          
          }
          

           

          The Delete Roles View

          Code for the Delete Roles View:
          @model AspNetExtendingIdentityRoles.Models.RoleViewModel
          
            
          
          @{
          
              ViewBag.Title = "Delete";
          
          }
          
            
          
          <h2>Delete</h2>
          
            
          
          <h3>Are you sure you want to delete this?</h3>
          
          <div>
          
              <h4>RolesViewModel</h4>
          
              <hr />
          
              <dl class="dl-horizontal">
          
                  <dt>
          
                      @Html.DisplayNameFor(model => model.RoleName)
          
                  </dt>
          
            
          
                  <dd>
          
                      @Html.DisplayFor(model => model.RoleName)
          
                  </dd>
          
            
          
                  <dt>
          
                      @Html.DisplayNameFor(model => model.Description)
          
                  </dt>
          
            
          
                  <dd>
          
                      @Html.DisplayFor(model => model.Description)
          
                  </dd>
          
            
          
              </dl>
          
            
          
              @using (Html.BeginForm()) {
          
                  @Html.AntiForgeryToken()
          
            
          
                  <div class="form-actions no-color">
          
                      <input type="submit" value="Delete" class="btn btn-default" /> |
          
                      @Html.ActionLink("Back to List", "Index")
          
                  </div>
          
              }
          
          </div>

           

          Modify _Layout.cshtml to Add Users and Roles Links

          I went ahead and modified the _Layout.cshtml file, changed what was the "Admin" link to simply "Users," and added a new "Roles" link as follows:

          Modify _Layout.cshtml:
          <div class="navbar-collapse collapse">
          
              <ul class="nav navbar-nav">
          
                  <li>@Html.ActionLink("Home", "Index", "Home")</li>
          
                  <li>@Html.ActionLink("About", "About", "Home")</li>
          
                  <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
          
                  <li>@Html.ActionLink("Users", "Index", "Account")</li>
          
                  <li>@Html.ActionLink("Roles", "Index", "Roles")</li>
          
              </ul>
          
              @Html.Partial("_LoginPartial")
          
          </div>

           

          Run Migrations and Build out the Database

          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:
          Update-Database

           

          Running the Application

          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:user-roles-view

           

          We can see, our new property is evident.

          Some Thoughts in Closing

          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.

          Pay Attention When Messing with Auth and Security!

          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.

          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.

          Got Any Thoughts? See Some Improvements?

          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!

          Additional Resources and Items of Interest

           

          Posted on February 13 2014 09:17 PM by jatten     

          Comments (8)

          Send Email to Selected Recipients from your ASP.NET MVC Web Application Part II

          Posted on January 18 2014 08:10 AM by jatten in ASP.NET MVC, ASP.Net, C#, CodeProject, Web   ||   Comments (0)

          tidepool-320This is the second part of an article demonstrating how to build out an application for sending personalized email to recipients selected from a list.

          In the first part, we put together the basic structure of our ASP.NET MVC application, according to a simple list of requirements.

          Now, we will add the email functionality, such that the user may select one or more recipients from a list using checkboxes, then generate and send a personalize email to each.

          Image by Sergio Quesada | Some Rights Reserved

          Review Part I --> Send Email to Selected Recipients from your ASP.NET MVC Web Application

          The Send Mail Method

          In the previous post, we created a stub for the SendMail method and threw some code in there to emulate a long-running process such as sending a list of emails:

          The Send Mail Method Stub:
          [HttpPost]
          
          [Authorize]
          
          public ActionResult SendMail(MailRecipientsViewModel recipients)
          
          {
          
              // Mail-sending code will happen here . . .
          
              System.Threading.Thread.Sleep(2000);
          
              return RedirectToAction("Index");
          
          }

           

          We did this so that we could run our application, and all the front end functionality would work as expected. Now let's see what we need to do in order to actually send some mail.

          The Problem to Solve

          Let's take a look at what we need to accomplish here by breaking the problem into steps. In order to send a personalized message to each of the recipients selected by the user, we need to:

          • Retrieve the recipient data for each of the recipients selected by the user
          • Compose a message personalized for each recipient by inserting the recipient's name into some sort of message template, and addressed to the recipient's email.
          • Retrieve the current User's email address to use as the "From" email address, and the current user's name to use in the signature
          • Represent the above as a "Message" which can be aggregated into a list of messages to be sent, addressed to each recipient.
          • Add a record to the SentMail table representing the key points for each email sent (basically a log)
          • When sending is complete, redirect to the Index page, and refresh, displaying updated records which include a filed for the date mail was most recently sent to each recipient.
          • Pass the list to some sort of Mail Sender, which can iterate over the list and send each message.

          Pseudo-Code the New and Improved SendMail Method

          Given the above, it looks like we might want our SendMail method to do something like this:

          Pseudo-Code for Steps in Sending Mail:
          [HttpPost]
          
          [Authorize]
          
          public ActionResult SendMail(MailRecipientsViewModel recipients)
          
          {
          
              // Retrieve the ids of the recipients selected:
          
            
          
              // Grab the recipient records:
          
            
          
              // Build the message container for each:
          
            
          
              // Send the mail:
          
            
          
              // Save a record of each mail sent:
          
            
          
              // Reload the index form:
          
          }
          

          So, lets make that happen!

          In order to keep our Action method clean and simple, we are going to make each of these steps a call to a locally defined method. The code for each step could then also be easily moved out of the controller into another class or classes, depending on the needs of your application and/or fussiness about how much work should be done within the controller itself. We aren't going to get all pedantic about it here.

          Retrieve the Selected Recipients

          We can start by thinking about what we actually receive in the recipients argument passed to SendMail from the HTTP request body. We will get back an instance of MailRecipientsViewModel, which provides a method getSelectedRecipientIds(). This returns an IEnumerable<int> representing the Ids of the recipients selected by the user on our form.

          Reviewing our MailRecipientsViewModel class:

          The Get Selected Recipient Ids Method:
          public class MailRecipientsViewModel
          
          {
          
              public List<SelectRecipientEditorViewModel> MailRecipients { get; set; }
          
              public MailRecipientsViewModel()
          
              {
          
                  this.MailRecipients = new List<SelectRecipientEditorViewModel>();
          
              }
          
            
          
            
          
              public IEnumerable<int> getSelectedRecipientIds()
          
              {
          
                  return (from r in this.MailRecipients 
          
                          where r.Selected 
          
                          select r.MailRecipientId).ToList();
          
              }
          
          }
          

           

          Private Implementation Code

          Now That we have our Ids, lets fill in the rest of our private helper methods. Add the following code the the controller after the SendMail stub:

          Adding Code to the Controller to Implement the Send Mail Method:
          IEnumerable<MailRecipient> LoadRecipientsFromIds(IEnumerable<int> selectedIds)
          
          {
          
              var selectedMailRecipients = from r in db.MailRecipients
          
                                           where selectedIds.Contains(r.MailRecipientId)
          
                                           select r;
          
              return selectedMailRecipients;
          
          }
          
            
          
            
          
          IEnumerable<Message> createRecipientMailMessages(
          
              IEnumerable<MailRecipient> selectedMailRecipients)
          
          {
          
              var messageContainers = new List<Message>();
          
              var currentUser = db.Users.Find(User.Identity.GetUserId());
          
              foreach (var recipient in selectedMailRecipients)
          
              {
          
                  var msg = new Message()
          
                  {
          
                      Recipient = recipient,
          
                      User = currentUser,
          
                      Subject = string.Format("Welcome, {0}", recipient.FullName),
          
                      MessageBody = this.getMessageText(recipient, currentUser)
          
                  };
          
                  messageContainers.Add(msg);
          
              }
          
              return messageContainers;
          
          }
          
            
          
            
          
          void SaveSentMail(IEnumerable<SentMail> sentMessages)
          
          {
          
              foreach (var sent in sentMessages)
          
              {
          
                  db.SentMails.Add(sent);
          
                  db.SaveChanges();
          
              }
          
          }
          
            
          
            
          
          string getMessageText(MailRecipient recipient, ApplicationUser user)
          
          {
          
              return ""
          
              + string.Format("Dear {0}, ", recipient.FullName) + Environment.NewLine
          
              + "Thank you for your interest in our latest product. "
          
              + "Please feel free to contact me for more information!"
          
              + Environment.NewLine
          
              + Environment.NewLine
          
              + "Sincerely, "
          
              + Environment.NewLine
          
              + string.Format("{0} {1}", user.FirstName, user.LastName);
          
          }

           

          Abstracting an Email Message - the Message Class

          In the code above, we see we create an instance of a class Message. This is another Model we need to add to our Models folder. We are using the Message class to represent everything needed to send an email:

          Add the following class to the Models folder:

          The Message Class:
          public class Message
          
          {
          
              public MailRecipient Recipient { get; set; }
          
              public ApplicationUser User { get; set; }
          
              public string Subject { get; set; }
          
              public string MessageBody { get; set; }
          
          }

           

          Also, in the createRecipientMailMessages method, we grab the current logged-in User with the following call:

          Get the Current Logged-in User:
          var currentUser = db.Users.Find(User.Identity.GetUserId());

           

          In order for this to work we need to add a reference to the Microsoft.AspNet.Identity namespace in the usings at the top of our code file, or this code won't work.

          Call Implementation Code from Send Mail Method

          Now that we have broken out each of our steps into discrete private method calls, we can call these from within the SendMail method:

          [HttpPost]
          
          [Authorize]
          
          public ActionResult SendMail(MailRecipientsViewModel recipients)
          
          {
          
              // Retrieve the ids of the recipients selected:
          
              var selectedIds = recipients.getSelectedRecipientIds();
          
            
          
              // Grab the recipient records:
          
              var selectedMailRecipients = this.LoadRecipientsFromIds(selectedIds);
          
            
          
              // Build the message container for each:
          
              var messageContainers = this.createRecipientMailMessages(selectedMailRecipients);
          
            
          
              // Send the mail:
          
              var sender = new MailSender();
          
              var sent = sender.SendMail(messageContainers);
          
            
          
              // Save a record of each mail sent:
          
              this.SaveSentMail(sent);
          
            
          
              // Reload the index form:
          
              return RedirectToAction("Index");
          
          }

           

          In the above, we have working code for everything except step 4, in which we initialize an instance of MailSender, and then actually send the mail. Now we get to the nitty-gritty of our application.

          The Mail Sender Class

          In our SendMail code, we build up a list of Message instances, which we then pass to a new class we haven't looked at yet - the MailSender class.

          Add a new class to the project, name it MailSender, and paste in the following code:

          The Mail Sender Class:
          public class MailSender
          
          {
          
              public IEnumerable<SentMail> SendMail(IEnumerable<Message> mailMessages)
          
              {
          
                  var output = new List<SentMail>();
          
            
          
                  // Modify this to suit your business case:
          
                  string mailUser = "youremail@outlook.com";
          
                  string mailUserPwd = "password";
          
                  SmtpClient client = new SmtpClient("smtp.host.com");
          
                  client.Port = 587;
          
                  client.DeliveryMethod = SmtpDeliveryMethod.Network;
          
                  client.UseDefaultCredentials = false;
          
                  System.Net.NetworkCredential credentials = 
          
                      new System.Net.NetworkCredential(mailUser, mailUserPwd);
          
                  client.EnableSsl = true;
          
                  client.Credentials = credentials;
          
            
          
                  foreach (var msg in mailMessages)
          
                  {
          
                      var mail = new MailMessage(msg.User.Email.Trim(), msg.Recipient.Email.Trim());
          
                      mail.Subject = msg.Subject;
          
                      mail.Body = msg.MessageBody;
          
            
          
                      try
          
                      {
          
                          client.Send(mail);
          
                          var sentMessage = new SentMail()
          
                          {
          
                              MailRecipientId = msg.Recipient.MailRecipientId,
          
                              SentToMail = msg.Recipient.Email,
          
                              SentFromMail = msg.User.Email,
          
                              SentDate = DateTime.Now
          
                          };
          
                          output.Add(sentMessage);
          
                      }
          
                      catch (Exception ex)
          
                      {
          
                          throw ex;
          
                          // Or, more likely, do some logging or something
          
                      }
          
                  }
          
                  return output;
          
              }
          
          }

           

          You will need to make sure you import the following namespaces for the code to work:

          Required Namespaces for the Mail Sender Class:
          using AspNetEmailExample.Models;
          
          using System;
          
          using System.Collections.Generic;
          
          using System.Net.Mail;

           

          Mail Client Configuration Settings

          I discuss the details of setting up the mail client for Outlook.com or Gmail in another post. For most mail hosts, the client configuration should resemble the above. However, pay attention. For one, as discussed in the post linked above, if you have some sort of two-step authorization in place on your mail host, you will likely need to use an Application-Specific Password for this to work. Also note, you can send mail using your Outlook.com account as a host, but unlike most other mail hosting accounts, the Outlook.com host name for SMTP is:

          smtp-mail.outlook.com

          Whereas Gmail is simply:

          smtp.gmail.com

           

          For other mail hosts, you may have to experiment a little, or consult the provider documentation.

          Walking Through the Execution of the Send Mail Method

          With all of our pieces in place, we can now walk through the execution of SendMail() and take an high-level look at what is going on in all these small, refactored methods, and how they align with the steps we defined to send mail to each recipient,

          First, we use our list of selected Ids to retrieve a corresponding list of fully instantiated recipient instances. This list is then returned to the call in SentMail, whereupon it is passed to the createMailRecipientMessages() method.

          This next method iterates the list of recipients, and creates a new Message instance for each, supplying the property values needed to send an email. Two of these, the User and MessageBody properties, involve additional calls. Retrieving the current user requires a call into the Microsoft.AspNet.Identity library.

          The getMessageText method, from which we retrieve the actual text for each mail message, represents a crude, "just make it work" implementation of what, in a real application, should probably be a template-based system. I have kept things simple here, but in reality we would probably like to be able to retrieve a message template from some resource or another, and populate the template properly from code without having to re-write and recompile.

          How you implement this would depend significantly on your application requirements and is beyond the scope of this article (this article is already long, considering the topic is not all that advanced!). If you have either questions, or brilliant ideas for implementing such a system in your own application, I would love to hear either. This might become the topic of another article.

          Once we have constructed our list of Message objects, we pass that to the MailSender.SendMail method, and, well, send the damn mail. We can see that each Message object is used to create a System.Net.Mail.MailMessage object, which is then sent using our properly configured mail client.

          Once each Message is sent, we create a SentMail object, and then return the list of List<SentMail> back to the SendMail controller method, at which point we persist the SentMail objects, and redirect back to the Index method.

          Running the Project and Sending Mail

          Now, we likely have our test data from before, when we entered some examples to test out our front-end. You may want to go ahead and change the example.com email addresses to an actual mail account you can access, to ensure all is working properly. Then, run the application, log in, and try the "Email Selected" button again. you may want to deselect one or two of the potential recipients in the list, just to see the difference:

          Try Sending Some Mail:

          try-sending-mail-before

          This time, we should see our "Busy" spinner for a moment, and then be redirected back to a refreshed Index view, now updated with the last date we sent mail to the selected recipients:

          The Updated Index View After Sending Mail:

          try-sending-mail-after

          As we can see, the two items selected for sending email have now been updated with a Last Sent date.

          What Went Wrong?

          If you have been following along, building this out as you go, and something doesn't work, I strongly recommend cloning the example project from source and trying to run that. For what appears to be a simple application, there are actually a lot of places where I may have missed some small but critical item in posting the code here on the blog. I've tried to balance providing everything you need to build this out yourself with keeping the article length manageable (and still semi-failed on the length part!).

          If you clone from source, and still have an issue, please do describe it in the comments section and/or shoot me an email. Also, if you see somewhere I have made a mistake, or taken the "dumb way" to doing something, I am ALL EARS.

          I've tried to combine providing a useful tutorial on the mechanics of sending mail from an application, with my own steps in thinking through the problem. Obviously, some of the content here is aimed at folks new to ASP.NET and/or Web Development in general.

          Thanks for reading, and your feedback is always appreciated.

          Additional Resources and Items of Interest

           

          Posted on January 18 2014 08:10 AM by jatten     

          Comments (0)

          About the author

          My name is John Atten, and my "handle" 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, and databases of many flavors. Actively learning always. I dig web development. I am always looking for new information, and value your feedback (especially where I got something wrong!). You can email me at:

          jatten at typecastexception dot com

          Web Hosting by