ASP.NET Identity 2.0: Implementing Group-Based Permissions Management

Posted on August 10 2014 07:35 PM by jatten in ASP.NET MVC, ASP.Net, C#, CodeProject   ||   Comments (4)

authorized-personel-onlyEarlier this year we looked at Implementing Group-Based Permissions Management using the ASP.NET Identity 1.0 framework. The objective of that project was to gain a little more granular control of application authorization, by treating the now-familiar Identity Role as more of a "permission" which could be granted to members of a group.

With the release of Identity 2.0 in March 2014 came some breaking changes, and a significant expansion of features and complexity. Identity 2.0 is now a full-grown authorization and authentication system for ASP.NET. However, the added features came at a price. There is a lot to get your mind around to start using Identity 2.0 effectively.

 

Image by Thomas Hawk  |  Some Rights Reserved

In previous articles, we have covered some of the basics:

The code we used to implement Group-based permissions under Identity 1.0 breaks in moving to Identity 2.0. Simply too much has changed between the two versions to make a clean, easy upgrade. In this article, we will revisit the Group-Based Permission idea, and implement the concept under the Identity 2.0 framework.

A Quick Review

Under the familiar ASP.NET Identity structure, Users are assigned one or more Roles. Traditionally, access to certain application functionality is governed, through the use of the [Authorize] attribute, by restricting access to certain controllers or controller methods to members of certain roles. This is effective as far as it goes, but does not lend itself to efficient management of more granular access permissions.

The Group-Based Permissions project attempts to find a middle ground between the complexities of a full-blown, Claims-based authorization scheme, and the simplicity (and limitations) of the authorization offered by Identity out of the box. Here, we will implement another familiar idea - Users are assigned to one or more Groups. Groups are granted set of permissions corresponding to the various authorizations required by group members to perform their function.

I discussed the overall concept, and security concerns in the previous article, so I won't rehash all that here. For reference, the following topics might be worth a quick visit:

In this article, we will implement a similar structure using Identity 2.0.

Getting Started - Clone a Handy Project Template

We're going to start with a handy, ready-to-customize project template based on the Identity Samples project created by the Identity team. I've used what we've learned in the past few posts to create a ready to extend project which can be cloned from my Github account (and hopefully soon, from Nuget!).

Or, Clone the Finished Source for this Project

Or, if you like, you can clone the source for the completed Group Permissions project, also on Github:

If you are starting with the template project and following along, it's probably best to rename the directory and project files to reflect the current effort. if you do this, make sure to also update the Web.Config file as well. You may want to update the connection string so that when the back-end database is created, the name reflects the Group Permissions application.

You MUST update the appSettings => owin:AppStartup element so that the startup assembly name matches the name you provide in Project => Properties => Assembly Name. In my case, I set my connection string and owin:appStartup as follows:

Update Web.Config Connection String and owin:appStartup elements:
<connectionStrings>
    <add name="DefaultConnection" 
         connectionString="Data Source=(LocalDb)\v11.0;
           Initial Catalog=AspNetIdentity2GroupPermissions-5;
           Integrated Security=SSPI" 
         providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings>
    <add key="owin:AppStartup" value="IdentitySample.Startup,AspNetIdentity2GRoupPermissions" />
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings></configuration>

 

Adding the Group Models

Let's get right to it. We can start by adding some new models to the Models => IdentityModels.cs file. We will be defining three different classes here: ApplicationGroup, which is the core Group model, as well as two additional classes which map ApplicationUser and ApplicationRole as collections within ApplicationGroup. Add the following to the IdentityModels.cs file:

The ApplicationGroup and Related Classes:
public class ApplicationGroup
{
    public ApplicationGroup()
    {
        this.Id = Guid.NewGuid().ToString();
        this.ApplicationRoles = new List<ApplicationGroupRole>();
        this.ApplicationUsers = new List<ApplicationUserGroup>();
    }
  
    public ApplicationGroup(string name)
        : this()
    {
        this.Name = name;
    }
  
    public ApplicationGroup(string name, string description)
        : this(name)
    {
        this.Description = description;
    }
  
    [Key]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<ApplicationGroupRole> ApplicationRoles { get; set; }
    public virtual ICollection<ApplicationUserGroup> ApplicationUsers { get; set; }
}
  
  
public class ApplicationUserGroup
{
    public string ApplicationUserId { get; set; }
    public string ApplicationGroupId { get; set; }
}
  
public class ApplicationGroupRole
{
    public string ApplicationGroupId { get; set; }
    public string ApplicationRoleId { get; set; }
}

 

Groups have a many-to-many relationship with both Users, and Roles. One user can belong to zero or more Groups, and one group can have zero or more users. Likewise with roles. A single role can be assigned to zero or more groups, and a single Group can have zero or more roles.

When we need to manage this type of relationship using EntityFramework, we can create what are essentially mapping classes, in this case, ApplicationUserGroup, and ApplicationGroupRole. The way we are doing this is similar to the structure used by the Identity team in defining Users, Roles, and UserRoles. For example, our ApplicationUser class is derived from IdentityUser, which defines a Roles property. Note that the Roles property of IdentityUser is not a collection of IdentityRole object, but instead a collection of IdentityUserRole objects. The difference being, the IdentityUserRole class defines only a UserId property, and a RoleId property.

We are doing the same thing here.We need to allow EF to manage the many-to-many relationships we described above by adding mapping classes between the collections defined on ApplicationGroup, and the domain objects involved in each relationship.

Override OnModelCreating in the DbContext Class

EntityFramework will not figure out our many-to-many relationships on its own, nor will it determine the proper table structures to create in our database. We need to help things along by overriding the OnModelCreating method in the ApplicationDbContext class. Also, we need to add ApplicationGroups as a property on our DbContext so that we can access our Groups from within our application.  Update the ApplicationDbContext class as follows:

Update ApplicationDbContext and Override OnModelCreating:
public class ApplicationDbContext
    : IdentityDbContext<ApplicationUser, ApplicationRole,
    string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
  
    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }
  
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
  
    // Add the ApplicationGroups property:
    public virtual IDbSet<ApplicationGroup> ApplicationGroups { get; set; }
  
    // Override OnModelsCreating:
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // Make sure to call the base method first:
        base.OnModelCreating(modelBuilder);
        
        // Map Users to Groups:
        modelBuilder.Entity<ApplicationGroup>()
            .HasMany<ApplicationUserGroup>((ApplicationGroup g) => g.ApplicationUsers)
            .WithRequired()
            .HasForeignKey<string>((ApplicationUserGroup ag) => ag.ApplicationGroupId);
        modelBuilder.Entity<ApplicationUserGroup>()
            .HasKey((ApplicationUserGroup r) => 
                new 
                { 
                    ApplicationUserId = r.ApplicationUserId, 
                    ApplicationGroupId = r.ApplicationGroupId 
                }).ToTable("ApplicationUserGroups");
  
        // Map Roles to Groups:
        modelBuilder.Entity<ApplicationGroup>()
            .HasMany<ApplicationGroupRole>((ApplicationGroup g) => g.ApplicationRoles)
            .WithRequired()
            .HasForeignKey<string>((ApplicationGroupRole ap) => ap.ApplicationGroupId);
        modelBuilder.Entity<ApplicationGroupRole>().HasKey((ApplicationGroupRole gr) => 
            new 
            { 
                ApplicationRoleId = gr.ApplicationRoleId, 
                ApplicationGroupId = gr.ApplicationGroupId 
            }).ToTable("ApplicationGroupRoles");
    }
}

 

With these humble beginnings in place, let's run the project, and see if everything works the way we expect.

Running the Project and Confirming Database Creation

If we run the project now, we will be greeted by the standard MVC page. Recall that with the Entity Framework Code-First model, database creation will occur at first data access. In other words, as things stand, we need to log in.

To this point, we haven't added any explicit functionality to our front-end site - when we log in, there will be no evidence that our underlying model has changed. We simply want to see if the site starts up properly, and that the database and table we expect are in fact created.

Once we have run the project and logged in, we should be able to stop, and use  the Visual Studio Server Explorer to see what our database tables look like. We should see something like the following:

Server Explorer with Additional Tables for Groups:

server-explorer-with-group-tables

We see from the above that our ApplicationGroup and related classes are now represented by tables in our back-end database, along with the expected columns and primary keys. So far, so good!

Investigation: Building a Consistent Asynchronous Model Architecture

APS.NET Identity 2.0 offers a fully async model architecture. We are going to do our best to follow the conventions established by the Identity team in building up our Groups management structure, using similar abstractions to create a Group store, and Group Manager with fully async methods. In other words, perhaps we can take a look at how the Identity 2.0 team built the basic UserStore and RoleStore abstractions (including the async methods) and simply model up our own GroupStore along the same lines.

If we take a close look at the structure used by the Identity team to build up the basic UserStore and RoleStore classes within the Identity framework, we find that each are composed around an instance of a class called EntityStore<TEntity> , which wraps the most basic behaviors expected of a persistence store.

For example, if we look inside the RoleStore<TRole, TKey, TUserRole> class defined as part of the Identity 2.0 framework, we find the following:

Decomposing the RoleStore Class:
public class RoleStore<TRole, TKey, TUserRole> : 
    IQueryableRoleStore<TRole, TKey>, IRoleStore<TRole, TKey>, IDisposable
    where TRole : IdentityRole<TKey, TUserRole>, new()
    where TUserRole : IdentityUserRole<TKey>, new()
{
    private bool _disposed;
    private EntityStore<TRole> _roleStore;
  
    public DbContext Context { get; private set; }
    public bool DisposeContext {get; set; }
  
    public IQueryable<TRole> Roles
    {
        get
        {
            return this._roleStore.EntitySet;
        }
    }
  
    public RoleStore(DbContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        this.Context = context;
        this._roleStore = new EntityStore<TRole>(context);
    }
  
    public virtual async Task CreateAsync(TRole role)
    {
        this.ThrowIfDisposed();
        if (role == null)
        {
            throw new ArgumentNullException("role");
        }
        this._roleStore.Create(role);
        TaskExtensions.CultureAwaiter<int> cultureAwaiter = 
            this.Context.SaveChangesAsync().WithCurrentCulture<int>();
        await cultureAwaiter;
    }
  
    public virtual async Task DeleteAsync(TRole role)
    {
        this.ThrowIfDisposed();
        if (role == null)
        {
            throw new ArgumentNullException("role");
        }
        this._roleStore.Delete(role);
        TaskExtensions.CultureAwaiter<int> cultureAwaiter = 
            this.Context.SaveChangesAsync().WithCurrentCulture<int>();
        await cultureAwaiter;
    }
  
    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
  
    protected virtual void Dispose(bool disposing)
    {
        if (this.DisposeContext && disposing && this.Context != null)
        {
            this.Context.Dispose();
        }
        this._disposed = true;
        this.Context = null;
        this._roleStore = null;
    }
  
    public Task<TRole> FindByIdAsync(TKey roleId)
    {
        this.ThrowIfDisposed();
        return this._roleStore.GetByIdAsync(roleId);
    }
  
    public Task<TRole> FindByNameAsync(string roleName)
    {
        this.ThrowIfDisposed();
        return QueryableExtensions
            .FirstOrDefaultAsync<TRole>(this._roleStore.EntitySet, 
                (TRole u) => u.Name.ToUpper() == roleName.ToUpper());
    }
  
    private void ThrowIfDisposed()
    {
        if (this._disposed)
        {
            throw new ObjectDisposedException(this.GetType().Name);
        }
    }
  
    public virtual async Task UpdateAsync(TRole role)
    {
        this.ThrowIfDisposed();
        if (role == null)
        {
            throw new ArgumentNullException("role");
        }
        this._roleStore.Update(role);
        TaskExtensions.CultureAwaiter<int> cultureAwaiter = 
            this.Context.SaveChangesAsync().WithCurrentCulture<int>();
        await cultureAwaiter;
    }
}

 

The code above is interesting, and we will be looking more closely in a bit. For the moment, notice the highlighted item. RoleStore wraps an instance of EntityStore<TRole> . If we follow our noses a little further, we find a definition for EntityStore as well:

The EntityStore Class from Identity 2.0 Framework:
internal class EntityStore<TEntity>
where TEntity : class
{
    public DbContext Context { get; private set; }
    public DbSet<TEntity> DbEntitySet { get; private set; }
    public IQueryable<TEntity> EntitySet
    {
        get
        {
            return this.DbEntitySet;
        }
    }
    public EntityStore(DbContext context)
    {
        this.Context = context;
        this.DbEntitySet = context.Set<TEntity>();
    }
    public void Create(TEntity entity)
    {
        this.DbEntitySet.Add(entity);
    }
    public void Delete(TEntity entity)
    {
        this.DbEntitySet.Remove(entity);
    }
    public virtual Task<TEntity> GetByIdAsync(object id)
    {
        return this.DbEntitySet.FindAsync(new object[] { id });
    }
    public virtual void Update(TEntity entity)
    {
        if (entity != null)
        {
            this.Context.Entry<TEntity>(entity).State = EntityState.Modified;
        }
    }

 

This code is also of great interest, despite its simplicity. Unfortunately, we cannot directly use the EntityStore class within our project. Note the internal modifier in the class declaration - this means EntityStore is only available to classes within the Microsoft.AspNet.Identity.EntityFramework assembly. In other words, we can't consume EntityStore in order to build up our own GroupStore implementation. Instead, we will take the time-honored approach of stealing/copying.

Building an Asynchronous GroupStore

We are going to apply the same conventions used by the Identity team in building out a GroupStore class, and then, in similar fashion, wrap a GroupManager class around THAT, much the same as Identity Framework wraps a RoleManager class around an instance of RoleStore.

But first, we need to deal with the EntityStore problem. in order to properly mimic the structure used to build up RoleStore and UserStore, we need to basically create our own implementation of EntityStore. In our case, we don't need a generically-typed class - we can create a non-generic implementation specific to our needs.

Mimicking EntityStore - Building the GroupStoreBase Class

We can basically steal most of the code from the EntityStore<TEntity> class shown above, and adapt it to suit our needs by removing the generic type arguments for the class itself, and by passing non-generic arguments where needed. Add a class named GroupStoreBase to the Models folder of your project, and then use the following code for the class itself. First, you will need the following using statements a the top of your code file:

Required Assembly References for the GroupStoreBase Class:
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;

 

The GroupStoreBase Class:
public class GroupStoreBase
{
    public DbContext Context { get; private set; }
    public DbSet<ApplicationGroup> DbEntitySet { get; private set; }
  
  
    public IQueryable<ApplicationGroup> EntitySet
    {
        get
        {
            return this.DbEntitySet;
        }
    }
  
  
    public GroupStoreBase(DbContext context)
    {
        this.Context = context;
        this.DbEntitySet = context.Set<ApplicationGroup>();
    }
  
  
    public void Create(ApplicationGroup entity)
    {
        this.DbEntitySet.Add(entity);
    }
  
  
    public void Delete(ApplicationGroup entity)
    {
        this.DbEntitySet.Remove(entity);
    }
  
  
    public virtual Task<ApplicationGroup> GetByIdAsync(object id)
    {
        return this.DbEntitySet.FindAsync(new object[] { id });
    }
  
  
    public virtual ApplicationGroup GetById(object id)
    {
        return this.DbEntitySet.Find(new object[] { id });
    }
  
  
    public virtual void Update(ApplicationGroup entity)
    {
        if (entity != null)
        {
            this.Context.Entry<ApplicationGroup>(entity).State = EntityState.Modified;
        }
    }
}

 

Note the structure here. the GroupStoreBase provides methods for working with a DbSet<ApplicationGroup> , but performs no persistence to the backside database directly. Persistence will be controlled by the next class in our structure, ApplicationGroupStore.

Building the Primary ApplicationGroupStore Class

In following the pattern used by UserStore and RoleStore, we will now build out a GroupStore class, which will be composed around our new GroupStoreBase class. Add another class to the models folder named ApplicationGroupStore, and add the following code:

The ApplicationGroupStore Class:
public class ApplicationGroupStore : IDisposable
{
    private bool _disposed;
    private GroupStoreBase _groupStore;
  
  
    public ApplicationGroupStore(DbContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        this.Context = context;
        this._groupStore = new GroupStoreBase(context);
    }
  
  
    public IQueryable<ApplicationGroup> Groups
    {
        get
        {
            return this._groupStore.EntitySet;
        }
    }
    
    public DbContext Context
    {
        get;
        private set;
    }
  
  
    public virtual void Create(ApplicationGroup group)
    {
        this.ThrowIfDisposed();
        if (group == null)
        {
            throw new ArgumentNullException("group");
        }
        this._groupStore.Create(group);
        this.Context.SaveChanges();
    }
  
  
    public virtual async Task CreateAsync(ApplicationGroup group)
    {
        this.ThrowIfDisposed();
        if (group == null)
        {
            throw new ArgumentNullException("group");
        }
        this._groupStore.Create(group);
        await this.Context.SaveChangesAsync();
    }
  
  
    public virtual async Task DeleteAsync(ApplicationGroup group)
    {
        this.ThrowIfDisposed();
        if (group == null)
        {
            throw new ArgumentNullException("group");
        }
        this._groupStore.Delete(group);
        await this.Context.SaveChangesAsync();
    }
  
  
    public virtual void Delete(ApplicationGroup group)
    {
        this.ThrowIfDisposed();
        if (group == null)
        {
            throw new ArgumentNullException("group");
        }
        this._groupStore.Delete(group);
        this.Context.SaveChanges();
    }
  
  
    public Task<ApplicationGroup> FindByIdAsync(string roleId)
    {
        this.ThrowIfDisposed();
        return this._groupStore.GetByIdAsync(roleId);
    }
  
  
    public ApplicationGroup FindById(string roleId)
    {
        this.ThrowIfDisposed();
        return this._groupStore.GetById(roleId);
    }
  
  
    public Task<ApplicationGroup> FindByNameAsync(string groupName)
    {
        this.ThrowIfDisposed();
        return QueryableExtensions
            .FirstOrDefaultAsync<ApplicationGroup>(this._groupStore.EntitySet, 
                (ApplicationGroup u) => u.Name.ToUpper() == groupName.ToUpper());
    }
  
  
    public virtual async Task UpdateAsync(ApplicationGroup group)
    {
        this.ThrowIfDisposed();
        if (group == null)
        {
            throw new ArgumentNullException("group");
        }
        this._groupStore.Update(group);
        await this.Context.SaveChangesAsync();
    }
  
  
    public virtual void Update(ApplicationGroup group)
    {
        this.ThrowIfDisposed();
        if (group == null)
        {
            throw new ArgumentNullException("group");
        }
        this._groupStore.Update(group);
        this.Context.SaveChanges();
    }
  
  
    // DISPOSE STUFF: ===============================================
  
    public bool DisposeContext
    {
        get;
        set;
    }
  
  
    private void ThrowIfDisposed()
    {
        if (this._disposed)
        {
            throw new ObjectDisposedException(this.GetType().Name);
        }
    }
  
   
    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }
  
  
    protected virtual void Dispose(bool disposing)
    {
        if (this.DisposeContext && disposing && this.Context != null)
        {
            this.Context.Dispose();
        }
        this._disposed = true;
        this.Context = null;
        this._groupStore = null;
    }
}

 

Some things to note about the ApplicationGroupStore class. First, notice that this class takes care of all the actual persistence to the backing store, by virtue of calls to .SaveChanges() or .SaveChangesAsync(). Also, we have provided both an async and a synchronous implementation for each of the methods.

However, we're not quite done yet. While the ApplicationGroupStore manages the basics of persistence for Groups, what it does NOT do is handle the complexities introduced by the relationships between Groups, Users, and Roles. Here, we can perform the basic CRUD operations on our groups, but we have no control over the relationships between the classes.

This becomes the job of the ApplicationGroupManager class.

Managing Complex Relationships - The ApplicationGroupManager Class

The relationships between Users, Groups, and Roles, for the sake of our application, are more complex than they might first appear.

Our Users-Groups-Roles structure is actually performing a bit of an illusion. It may appear, when we are done, that Roles will "belong" to groups, and that Users, by virtue of membership in a particular group, gain access to the Roles of that Group. However, what is really going on is that, when a User is assigned to a particular group, our application is then adding that user to each Role within the Group.

This is a subtle, but important distinction.

Let's assume we have an existing Group with two Roles assigned - "CanEditAccount" and "CanViewAccount." Let's further assume that there are three users in this group. Finally, let's say we want to add another (already existing) Role to this group - "CanDeleteAccount." What needs to happen?

  1. We assign the role to the group
  2. We need to add each member or the group to the new role

On the face of it, that is relatively straightforward. However, each User can belong to more than one group. Also, a Role can be assigned to more than one group. What if we want to remove a Role from a group?

  1. Remove each User in the Group from the Role, except when they are also a member of another group which also has that same role
  2. Remove the Role from the Group

This is a little more complicated. A similar situation arises if we wish to remove a User from a Group:

  1. Remove the User from all Roles in the Group, except when the user also belongs to another Group with the same role
  2. Remove the User from the Group

And so on. In order to get the predictable, intuitive behavior from our application which will be expected by the end user, there is more going on than meets the eye.

It will be the job of the ApplicationGroupManager to handle these types of problems for us, and afford a clear API against which our controllers can work between the user and the backside data.

We have created the GroupStore class to handle the basic persistence of Group data, and we have the ApplicationUserManager and ApplicationRoleManager classes to handle the relationships between Users, Roles, and persistence. For the most part, the ApplicationGroupManager's job will mainly be governing the interactions of these three stores, and occasionally the DbContext directly.

We will accomplish this by defining an API which, similar to the Identity base classes UserManager and RoleManager, affords us the intuitive methods we need to deal with Group-based Role management. We will provide both synchronous and asynchronous implementations.

Add another class to the Models folder, and name it ApplicationGroupManager. You will need the following using statements at the top of your code file:

Required Assembly References for ApplicationGroupManager:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;

 

Now, add the following code:

The ApplicationGroupManager Class:
public class ApplicationGroupManager
{
    private ApplicationGroupStore _groupStore;
    private ApplicationDbContext _db;
    private ApplicationUserManager _userManager;
    private ApplicationRoleManager _roleManager;
  
    public ApplicationGroupManager()
    {
        _db = HttpContext.Current
            .GetOwinContext().Get<ApplicationDbContext>();
        _userManager = HttpContext.Current
            .GetOwinContext().GetUserManager<ApplicationUserManager>();
        _roleManager = HttpContext.Current
            .GetOwinContext().Get<ApplicationRoleManager>();
        _groupStore = new ApplicationGroupStore(_db);
    }
  
  
    public IQueryable<ApplicationGroup> Groups
    {
        get
        {
            return _groupStore.Groups;
        }
    }
  
  
    public async Task<IdentityResult> CreateGroupAsync(ApplicationGroup group)
    {
        await _groupStore.CreateAsync(group);
        return IdentityResult.Success;
    }
  
 
    public IdentityResult CreateGroup(ApplicationGroup group)
    {
        _groupStore.Create(group);
        return IdentityResult.Success;
    }
  
  
    public IdentityResult SetGroupRoles(string groupId, params string[] roleNames)
    {
        // Clear all the roles associated with this group:
        var thisGroup = this.FindById(groupId);
        thisGroup.ApplicationRoles.Clear();
        _db.SaveChanges();
  
        // Add the new roles passed in:
        var newRoles = _roleManager.Roles.Where(r => roleNames.Any(n => n == r.Name));
        foreach(var role in newRoles)
        {
            thisGroup.ApplicationRoles.Add(new ApplicationGroupRole 
            { 
                ApplicationGroupId = groupId, 
                ApplicationRoleId = role.Id 
            });
        }
        _db.SaveChanges();
  
        // Reset the roles for all affected users:
        foreach(var groupUser in thisGroup.ApplicationUsers)
        {
            this.RefreshUserGroupRoles(groupUser.ApplicationUserId);
        }
        return IdentityResult.Success;
    }
  
  
    public async Task<IdentityResult> SetGroupRolesAsync(
        string groupId, params string[] roleNames)
    {
        // Clear all the roles associated with this group:
        var thisGroup = await this.FindByIdAsync(groupId);
        thisGroup.ApplicationRoles.Clear();
        await _db.SaveChangesAsync();
  
        // Add the new roles passed in:
        var newRoles = _roleManager.Roles
                        .Where(r => roleNames.Any(n => n == r.Name));
        foreach (var role in newRoles)
        {
            thisGroup.ApplicationRoles.Add(new ApplicationGroupRole 
            { 
                ApplicationGroupId = groupId, 
                ApplicationRoleId = role.Id 
            });
        }
        await _db.SaveChangesAsync();
  
        // Reset the roles for all affected users:
        foreach (var groupUser in thisGroup.ApplicationUsers)
        {
            await this.RefreshUserGroupRolesAsync(groupUser.ApplicationUserId);
        }
        return IdentityResult.Success;
    }
  
  
    public async Task<IdentityResult> SetUserGroupsAsync(
        string userId, params string[] groupIds)
    {
        // Clear current group membership:
        var currentGroups = await this.GetUserGroupsAsync(userId);
        foreach (var group in currentGroups)
        {
            group.ApplicationUsers
                .Remove(group.ApplicationUsers
                .FirstOrDefault(gr => gr.ApplicationUserId == userId
            ));
        }
        await _db.SaveChangesAsync();
  
        // Add the user to the new groups:
        foreach (string groupId in groupIds)
        {
            var newGroup = await this.FindByIdAsync(groupId);
            newGroup.ApplicationUsers.Add(new ApplicationUserGroup 
            { 
                ApplicationUserId = userId, 
                ApplicationGroupId = groupId 
            });
        }
        await _db.SaveChangesAsync();
  
        await this.RefreshUserGroupRolesAsync(userId);
        return IdentityResult.Success;
    }
  
  
    public IdentityResult SetUserGroups(string userId, params string[] groupIds)
    {
        // Clear current group membership:
        var currentGroups = this.GetUserGroups(userId);
        foreach(var group in currentGroups)
        {
            group.ApplicationUsers
                .Remove(group.ApplicationUsers
                .FirstOrDefault(gr => gr.ApplicationUserId == userId
            ));
        }
        _db.SaveChanges();
  
        // Add the user to the new groups:
        foreach(string groupId in groupIds)
        {
            var newGroup = this.FindById(groupId);
            newGroup.ApplicationUsers.Add(new ApplicationUserGroup 
            { 
                ApplicationUserId = userId, 
                ApplicationGroupId = groupId 
            });
        }
        _db.SaveChanges();
  
        this.RefreshUserGroupRoles(userId);
        return IdentityResult.Success;
    }
  
  
    public IdentityResult RefreshUserGroupRoles(string userId)
    {
        var user = _userManager.FindById(userId);
        if(user == null)
        {
            throw new ArgumentNullException("User");
        }
        // Remove user from previous roles:
        var oldUserRoles = _userManager.GetRoles(userId);
        if(oldUserRoles.Count > 0)
        {
            _userManager.RemoveFromRoles(userId, oldUserRoles.ToArray());
        }
  
        // Find teh roles this user is entitled to from group membership:
        var newGroupRoles = this.GetUserGroupRoles(userId);
  
        // Get the damn role names:
        var allRoles = _roleManager.Roles.ToList();
        var addTheseRoles = allRoles
            .Where(r => newGroupRoles.Any(gr => gr.ApplicationRoleId == r.Id
        ));
        var roleNames = addTheseRoles.Select(n => n.Name).ToArray();
  
        // Add the user to the proper roles
        _userManager.AddToRoles(userId, roleNames);
  
        return IdentityResult.Success;
    }
  
  
    public async Task<IdentityResult> RefreshUserGroupRolesAsync(string userId)
    {
        var user = await _userManager.FindByIdAsync(userId);
        if (user == null)
        {
            throw new ArgumentNullException("User");
        }
        // Remove user from previous roles:
        var oldUserRoles = await _userManager.GetRolesAsync(userId);
        if (oldUserRoles.Count > 0)
        {
            await _userManager.RemoveFromRolesAsync(userId, oldUserRoles.ToArray());
        }
  
        // Find the roles this user is entitled to from group membership:
        var newGroupRoles = await this.GetUserGroupRolesAsync(userId);
  
        // Get the damn role names:
        var allRoles = await _roleManager.Roles.ToListAsync();
        var addTheseRoles = allRoles
            .Where(r => newGroupRoles.Any(gr => gr.ApplicationRoleId == r.Id
        ));
        var roleNames = addTheseRoles.Select(n => n.Name).ToArray();
  
        // Add the user to the proper roles
        await _userManager.AddToRolesAsync(userId, roleNames);
  
        return IdentityResult.Success;
    }
  
  
    public async Task<IdentityResult> DeleteGroupAsync(string groupId)
    {
        var group = await this.FindByIdAsync(groupId);
        if (group == null)
        {
            throw new ArgumentNullException("User");
        }
  
        var currentGroupMembers = (await this.GetGroupUsersAsync(groupId)).ToList();
        // remove the roles from the group:
        group.ApplicationRoles.Clear();
  
        // Remove all the users:
        group.ApplicationUsers.Clear();
  
        // Remove the group itself:
        _db.ApplicationGroups.Remove(group);
  
        await _db.SaveChangesAsync();
  
        // Reset all the user roles:
        foreach (var user in currentGroupMembers)
        {
            await this.RefreshUserGroupRolesAsync(user.Id);
        }
        return IdentityResult.Success;
    }
  
  
    public IdentityResult DeleteGroup(string groupId)
    {
        var group = this.FindById(groupId);
        if(group == null)
        {
            throw new ArgumentNullException("User");
        }
  
        var currentGroupMembers = this.GetGroupUsers(groupId).ToList();
        // remove the roles from the group:
        group.ApplicationRoles.Clear();
  
        // Remove all the users:
        group.ApplicationUsers.Clear();
  
        // Remove the group itself:
        _db.ApplicationGroups.Remove(group);
  
        _db.SaveChanges();
  
        // Reset all the user roles:
        foreach(var user in currentGroupMembers)
        {
            this.RefreshUserGroupRoles(user.Id);
        }
        return IdentityResult.Success;
    }
  
  
    public async Task<IdentityResult> UpdateGroupAsync(ApplicationGroup group)
    {
        await _groupStore.UpdateAsync(group);
        foreach (var groupUser in group.ApplicationUsers)
        {
            await this.RefreshUserGroupRolesAsync(groupUser.ApplicationUserId);
        }
        return IdentityResult.Success;
    }
  
  
    public IdentityResult UpdateGroup(ApplicationGroup group)
    {
        _groupStore.Update(group);
        foreach(var groupUser in group.ApplicationUsers)
        {
            this.RefreshUserGroupRoles(groupUser.ApplicationUserId);
        }
        return IdentityResult.Success;
    }
  
  
    public IdentityResult ClearUserGroups(string userId)
    {
        return this.SetUserGroups(userId, new string[] { });
    }
  
  
    public async Task<IdentityResult> ClearUserGroupsAsync(string userId)
    {
        return await this.SetUserGroupsAsync(userId, new string[] { });
    }
  
  
    public async Task<IEnumerable<ApplicationGroup>> GetUserGroupsAsync(string userId)
    {
        var result = new List<ApplicationGroup>();
        var userGroups = (from g in this.Groups
                          where g.ApplicationUsers
                            .Any(u => u.ApplicationUserId == userId)
                          select g).ToListAsync();
        return await userGroups;
    }
  
  
    public IEnumerable<ApplicationGroup> GetUserGroups(string userId)
    {
        var result = new List<ApplicationGroup>();
        var userGroups = (from g in this.Groups
                          where g.ApplicationUsers
                            .Any(u => u.ApplicationUserId == userId)
                          select g).ToList();
        return userGroups;
    }
  
  
    public async Task<IEnumerable<ApplicationRole>> GetGroupRolesAsync(
        string groupId)
    {
        var grp = await _db.ApplicationGroups
            .FirstOrDefaultAsync(g => g.Id == groupId);
        var roles = await _roleManager.Roles.ToListAsync();
        var groupRoles = (from r in roles
                          where grp.ApplicationRoles
                            .Any(ap => ap.ApplicationRoleId == r.Id)
                          select r).ToList();
        return groupRoles;
    }
  
  
    public IEnumerable<ApplicationRole> GetGroupRoles(string groupId)
    {
        var grp = _db.ApplicationGroups.FirstOrDefault(g => g.Id == groupId);
        var roles = _roleManager.Roles.ToList();
        var groupRoles = from r in roles
                         where grp.ApplicationRoles
                            .Any(ap => ap.ApplicationRoleId == r.Id)
                         select r;
        return groupRoles;
    }
  
  
    public IEnumerable<ApplicationUser> GetGroupUsers(string groupId)
    {
        var group = this.FindById(groupId);
        var users = new List<ApplicationUser>();
        foreach (var groupUser in group.ApplicationUsers)
        {
            var user = _db.Users.Find(groupUser.ApplicationUserId);
            users.Add(user);
        }
        return users;
    }
  
  
    public async Task<IEnumerable<ApplicationUser>> GetGroupUsersAsync(string groupId)
    {
        var group = await this.FindByIdAsync(groupId);
        var users = new List<ApplicationUser>();
        foreach (var groupUser in group.ApplicationUsers)
        {
            var user = await _db.Users
                .FirstOrDefaultAsync(u => u.Id == groupUser.ApplicationUserId);
            users.Add(user);
        }
        return users;
    }
  
  
    public IEnumerable<ApplicationGroupRole> GetUserGroupRoles(string userId)
    {
        var userGroups = this.GetUserGroups(userId);
        var userGroupRoles = new List<ApplicationGroupRole>();
        foreach(var group in userGroups)
        {
            userGroupRoles.AddRange(group.ApplicationRoles.ToArray());
        }
        return userGroupRoles;
    }
  
  
    public async Task<IEnumerable<ApplicationGroupRole>> GetUserGroupRolesAsync(
        string userId)
    {
        var userGroups = await this.GetUserGroupsAsync(userId);
        var userGroupRoles = new List<ApplicationGroupRole>();
        foreach (var group in userGroups)
        {
            userGroupRoles.AddRange(group.ApplicationRoles.ToArray());
        }
        return userGroupRoles;
    }
  
  
    public async Task<ApplicationGroup> FindByIdAsync(string id)
    {
        return await _groupStore.FindByIdAsync(id);
    }
  
  
    public ApplicationGroup FindById(string id)
    {
        return _groupStore.FindById(id);
    }
}

 

As we can see from the above, there's a lot of code there. However, much of it is due to duplication between synchronous and asynchronous method implementations. With the above, we now have an API to work against from our controllers, and we can now get down to brass tacks, and add the Groups functionality to our site.

We've kept things as simple as possible in terms of adding and removing Users from Groups, Roles to and from Groups, and such. As you can see, each time we change the groups a user belongs to, we change all the group assignments at once, by calling SetUserGroups() and passing in an array of Group Id's. Similarly, we assign all of the Roles to a group in one shot by calling SetGroupRoles() and again, passing in an array of Role names, representing all of the roles assigned to a particular group.

We do these in this manner because, when we modify a User's Group membership, we need to essentially re-set all of the User's Roles anyway. In like manner, when we modify the Roles assigned to a particular group, we need to refresh the Roles assigned to every user within that group.

This is also handy because, when we receive the User and/or Role selections made by the user from either of the Admin Views, we get them as an array anyway. We'll see this more closely in a bit.

Adding a GroupViewModel

We will need a view model for passing group data between various controller methods and their associated Views. in the Models => AdminViewModel.cs file, add the following class:

The GroupVeiwModel Class:
public class GroupViewModel
{
    public GroupViewModel()
    {
        this.UsersList = new List<SelectListItem>();
        this.PermissionsList = new List<SelectListItem>();
    }
    [Required(AllowEmptyStrings = false)]
    public string Id { get; set; }
    [Required(AllowEmptyStrings = false)]
    public string Name { get; set; }
    public string Description { get; set; }
    public ICollection<SelectListItem> UsersList { get; set; }
    public ICollection<SelectListItem> RolesList { get; set; }
}

 

Notice here that we are passing ICollection<SelectListItem> to represent Users and Roles assigned to a Group. This way, we can pass a list of user names or or role names out to a view, allow the user to select one or more items from the list, and then process the selection choices made when the form data is submitted back to the controller via the HTTP POST method.

Update the EditUserViewModel

While we have the AdminViewModel.cs file open, let's also modify the EditUserViewModel, and add a collection property for Groups:

Add a GroupsList Property to EditUserViewModel:
public class EditUserViewModel
{
    public EditUserViewModel()
    {
        this.RolesList = new List<SelectListItem>();
        this.GroupsList = new List<SelectListItem>();
    }
    public string Id { get; set; }
    [Required(AllowEmptyStrings = false)]
    [Display(Name = "Email")]
    [EmailAddress]
    public string Email { get; set; }
  
    // We will still use this, so leave it here:
    public ICollection<SelectListItem> RolesList { get; set; }
  
    // Add a GroupsList Property:
    public ICollection<SelectListItem> GroupsList { get; set; }
}

 

We will keep the RolesList collection as well. Even though we won't be assigning Roles directly to Users anymore, we may want to create a View which allows us to see what Roles a user has by virtue of membership in various Groups. This way, we can use the same ViewModel.

Now that we have our ViewModel all tuned up, let's add a GroupsAdminController.

Building the GroupsAdminController

Similar to the existing UserAdminController and the RolesAdminController, we need to provide a Controller to work with our new Groups functionality.

We need to add a controller in the Controllers directory. Instead of using the Context Menu => Add Controller method, just add a class, named GroupsAdminController, and add the following code:

Adding the GroupsAdminController:
public class GroupsAdminController : Controller
{
    private ApplicationDbContext db = new ApplicationDbContext();
  
    private ApplicationGroupManager _groupManager;
    public ApplicationGroupManager GroupManager
    {
        get
        {
            return _groupManager ?? new ApplicationGroupManager();
        }
        private set
        {
            _groupManager = value;
        }
    }
  
    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext()
                .Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }
  
  
    public ActionResult Index()
    {
        return View(this.GroupManager.Groups.ToList());
    } 
  
  
    public async Task<ActionResult> Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ApplicationGroup applicationgroup =
            await this.GroupManager.Groups.FirstOrDefaultAsync(g => g.Id == id);
        if (applicationgroup == null)
        {
            return HttpNotFound();
        }
        var groupRoles = this.GroupManager.GetGroupRoles(applicationgroup.Id);
        string[] RoleNames = groupRoles.Select(p => p.Name).ToArray();
        ViewBag.RolesList = RoleNames;
        ViewBag.RolesCount = RoleNames.Count();
        return View(applicationgroup);
    }
  
  
    public ActionResult Create()
    {
        //Get a SelectList of Roles to choose from in the View:
        ViewBag.RolesList = new SelectList(
            this.RoleManager.Roles.ToList(), "Id", "Name");
        return View();
    }
  
  
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create(
        [Bind(Include = "Name,Description")] ApplicationGroup applicationgroup, 
        params string[] selectedRoles)
    {
        if (ModelState.IsValid)
        {
            // Create the new Group:
            var result = await this.GroupManager.CreateGroupAsync(applicationgroup);
            if (result.Succeeded)
            {
                selectedRoles = selectedRoles ?? new string[] { };
  
                // Add the roles selected:
                await this.GroupManager
                    .SetGroupRolesAsync(applicationgroup.Id, selectedRoles);
            }
            return RedirectToAction("Index");
        }
 
        // Otherwise, start over:
        ViewBag.RoleId = new SelectList(
            this.RoleManager.Roles.ToList(), "Id", "Name");
        return View(applicationgroup);
    }
  
  
    public async Task<ActionResult> Edit(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ApplicationGroup applicationgroup = await this.GroupManager.FindByIdAsync(id);
        if (applicationgroup == null)
        {
            return HttpNotFound();
        }
  
        // Get a list, not a DbSet or queryable:
        var allRoles = await this.RoleManager.Roles.ToListAsync();
        var groupRoles = await this.GroupManager.GetGroupRolesAsync(id);
  
        var model = new GroupViewModel()
        {
            Id = applicationgroup.Id,
            Name = applicationgroup.Name,
            Description = applicationgroup.Description
        };
  
        // load the roles/Roles for selection in the form:
        foreach (var Role in allRoles)
        {
            var listItem = new SelectListItem()
            {
                Text = Role.Name,
                Value = Role.Id,
                Selected = groupRoles.Any(g => g.Id == Role.Id)
            };
            model.RolesList.Add(listItem);
        }
        return View(model);
    }
  
  
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(
        [Bind(Include = "Id,Name,Description")] GroupViewModel model, 
        params string[] selectedRoles)
    {
        var group = await this.GroupManager.FindByIdAsync(model.Id);
        if (group == null)
        {
            return HttpNotFound();
        }
        if (ModelState.IsValid)
        {
            group.Name = model.Name;
            group.Description = model.Description;
            await this.GroupManager.UpdateGroupAsync(group);
  
            selectedRoles = selectedRoles ?? new string[] { };
            await this.GroupManager.SetGroupRolesAsync(group.Id, selectedRoles);
            return RedirectToAction("Index");
        }
        return View(model);
    }
  
  
    public async Task<ActionResult> Delete(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ApplicationGroup applicationgroup = await this.GroupManager.FindByIdAsync(id);
        if (applicationgroup == null)
        {
            return HttpNotFound();
        }
        return View(applicationgroup);
    }
  
  
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        ApplicationGroup applicationgroup = await this.GroupManager.FindByIdAsync(id);
        await this.GroupManager.DeleteGroupAsync(id);
        return RedirectToAction("Index");
    }
  
  
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}

 

As we can see, we use the GroupsAdminController to manage the creation of groups, and the assignment of roles to various groups. Now, we need to modify the UsersAdminController so that instead of assigning Users to Roles directly, we are instead assigning Users to Groups, through which they gain access to the roles assigned to each group.

Modify the UsersAdminController

We need to make a few adjustments to the UsersAdminController to reflect the manner in which we are managing Groups and Roles. As mentioned previously, we are now assigning users to Groups instead of directly to roles, and our UsersAdminController needs to reflect this.

First off, we need to add an instance of ApplicationGroupManager to the controller. Next, we need to update all of our controller methods to consume Groups instead of Roles. When we create a new User, we want the View to include a list of available Groups to which the User might be assigned. When we Edit an existing User, we want the option to modify group assignments. When we Delete a user, we need to make sure the corresponding Group relationships are deleted as well.

The Following is the updated code for the entire UsersAdminController. It is easier to copy the entire thing in than to wade through it piece by piece. Then you can eyeball things, and fairly easily understand what is going on in each controller method. 

The Modified UsersAdminController:
[Authorize(Roles = "Admin")]
public class UsersAdminController : Controller
{
    public UsersAdminController()
    {
    }
  
    public UsersAdminController(ApplicationUserManager userManager, 
        ApplicationRoleManager roleManager)
    {
        UserManager = userManager;
        RoleManager = roleManager;
    }
  
    private ApplicationUserManager _userManager;
    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext()
                .GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }
  
    // Add the Group Manager (NOTE: only access through the public
    // Property, not by the instance variable!)
    private ApplicationGroupManager _groupManager;
    public ApplicationGroupManager GroupManager
    {
        get
        {
            return _groupManager ?? new ApplicationGroupManager();
        }
        private set
        {
            _groupManager = value;
        }
    }
  
    private ApplicationRoleManager _roleManager;
    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext()
                .Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }
  
      
    public async Task<ActionResult> Index()
    {
        return View(await UserManager.Users.ToListAsync());
    }
  
  
    public async Task<ActionResult> Details(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var user = await UserManager.FindByIdAsync(id);
  
        // Show the groups the user belongs to:
        var userGroups = await this.GroupManager.GetUserGroupsAsync(id);
        ViewBag.GroupNames = userGroups.Select(u => u.Name).ToList();
        return View(user);
    }
  
  
    public ActionResult Create()
    {
        // Show a list of available groups:
        ViewBag.GroupsList = 
            new SelectList(this.GroupManager.Groups, "Id", "Name");
        return View();
    }
  
  
    [HttpPost]
    public async Task<ActionResult> Create(RegisterViewModel userViewModel, 
        params string[] selectedGroups)
    {
        if (ModelState.IsValid)
        {
            var user = new ApplicationUser 
            { 
                UserName = userViewModel.Email, 
                Email = userViewModel.Email 
            };
            var adminresult = await UserManager
                .CreateAsync(user, userViewModel.Password);
  
            //Add User to the selected Groups 
            if (adminresult.Succeeded)
            {
                if (selectedGroups != null)
                {
                    selectedGroups = selectedGroups ?? new string[] { };
                    await this.GroupManager
                        .SetUserGroupsAsync(user.Id, selectedGroups);
                }
                return RedirectToAction("Index");
            }
        }
        ViewBag.Groups = new SelectList(
            await RoleManager.Roles.ToListAsync(), "Id", "Name");
        return View();
    }
  
  
    public async Task<ActionResult> Edit(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var user = await UserManager.FindByIdAsync(id);
        if (user == null)
        {
            return HttpNotFound();
        }
  
        // Display a list of available Groups:
        var allGroups = this.GroupManager.Groups;
        var userGroups = await this.GroupManager.GetUserGroupsAsync(id);
  
        var model = new EditUserViewModel()
        {
            Id = user.Id,
            Email = user.Email
        };
  
        foreach (var group in allGroups)
        {
            var listItem = new SelectListItem()
            {
                Text = group.Name,
                Value = group.Id,
                Selected = userGroups.Any(g => g.Id == group.Id)
            };
            model.GroupsList.Add(listItem);
        }
        return View(model);
    }
  
  
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(
        [Bind(Include = "Email,Id")] EditUserViewModel editUser, 
        params string[] selectedGroups)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByIdAsync(editUser.Id);
            if (user == null)
            {
                return HttpNotFound();
            }
  
            // Update the User:
            user.UserName = editUser.Email;
            user.Email = editUser.Email;
            await this.UserManager.UpdateAsync(user);
  
            // Update the Groups:
            selectedGroups = selectedGroups ?? new string[] { };
            await this.GroupManager.SetUserGroupsAsync(user.Id, selectedGroups);
            return RedirectToAction("Index");
        }
        ModelState.AddModelError("", "Something failed.");
        return View();
    }
  
  
    public async Task<ActionResult> Delete(string id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        var user = await UserManager.FindByIdAsync(id);
        if (user == null)
        {
            return HttpNotFound();
        }
        return View(user);
    }
  
  
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> DeleteConfirmed(string id)
    {
        if (ModelState.IsValid)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
  
            var user = await UserManager.FindByIdAsync(id);
            if (user == null)
            {
                return HttpNotFound();
            }
  
            // Remove all the User Group references:
            await this.GroupManager.ClearUserGroupsAsync(id);
  
            // Then Delete the User:
            var result = await UserManager.DeleteAsync(user);
            if (!result.Succeeded)
            {
                ModelState.AddModelError("", result.Errors.First());
                return View();
            }
            return RedirectToAction("Index");
        }
        return View();
    }
}

 

Now that we have all of our Controllers in place, we need to add and/or update some Views.

Add Groups Admin as a Menu Item in the Main Layout View

In order to access our new Groups, we will need to add a menu item to Views => Shared => _Layout.cshtml. Since we only want Admin users to access menu item, we want to tuck it in with the other links to Admin-type Views. Modify the _Layout.cshtml file as follows (I've only included the relevant section of the View template below):

Add Groups Admin as a Link in the Main Layout View:
// Other View Code before...:
   
<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>
   
    @if (Request.IsAuthenticated && User.IsInRole("Admin")) {
        <li>@Html.ActionLink("RolesAdmin", "Index", "RolesAdmin")</li>
        <li>@Html.ActionLink("UsersAdmin", "Index", "UsersAdmin")</li>
        <li>@Html.ActionLink("GroupsAdmin", "Index", "GroupsAdmin")</li>
    }
</ul>
@Html.Partial("_LoginPartial")
   
// ...Other View Code After...

 

Adding Views for the GroupsAdminController

We're going to step through this fairly quickly, since there isn't a lot of discussion needed around View template code. Obviously, we need a view for each of our GroupsAdminController action methods.

Since Visual Studio won't generate quite what we need using the Add View Context Menu command, we'll do this manually.

Add a folder to the Views directory named GroupsAdmin. Now add the following Views:

The GroupsAdmin Index.cshtml View:
@model IEnumerable<IdentitySample.Models.ApplicationGroup>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Description)
        </th>
        <th></th>
    </tr>
  
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.Description)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
            @Html.ActionLink("Details", "Details", new { id=item.Id }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.Id })
        </td>
    </tr>
}
</table>

 

The GroupsAdmin Create.chtml View:
@model IdentitySample.Models.ApplicationGroup
  
@{
    ViewBag.Title = "Create";
}
  
<h2>Create</h2>
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
     
    <div class="form-horizontal">
        <h4>ApplicationGroup</h4>
        <hr />
        @Html.ValidationSummary(true)
        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </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">
            <label class="col-md-2 control-label">
                Select Group Roles
            </label>
            <div class="col-md-10">
                @foreach (var item in (SelectList)ViewBag.RolesList)
                {
                    <div>
                        <input type="checkbox" name="SelectedRoles" value="@item.Text" class="checkbox-inline" />
                        @Html.Label(item.Text, new { @class = "control-label" })
                    </div>
                }
            </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 GroupsAdmin Edit.cshtml View:
@model IdentitySample.Models.GroupViewModel
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
     
    <div class="form-horizontal">
        <h4>ApplicationGroup</h4>
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)
  
        <div class="form-group">
            @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name)
                @Html.ValidationMessageFor(model => model.Name)
            </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">
            @Html.Label("Permissions", new { @class = "control-label col-md-2" })
            <span class=" col-md-10">
                @foreach (var item in Model.RolesList)
                {
                    <div>
                        <input type="checkbox" name="selectedRoles" value="@item.Text" checked="@item.Selected" class="checkbox-inline" />
                        @Html.Label(item.Text, new { @class = "control-label" })
                    </div>
                }
            </span>
        </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 GroupsAdmin Details.cshtml View:
@model IdentitySample.Models.ApplicationGroup
  
@{
    ViewBag.Title = "Details";
}
  
<h2>Details</h2>
  
<div>
    <h4>ApplicationGroup</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
  
        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>
  
        <dt>
            @Html.DisplayNameFor(model => model.Description)
        </dt>
  
        <dd>
            @Html.DisplayFor(model => model.Description)
        </dd>
  
    </dl>
</div>
  
<h4>List of permissions granted this group</h4>
@if (ViewBag.PermissionsCount == 0)
{
    <hr />
    <p>No users found in this role.</p>
}
  
<table class="table">
  
    @foreach (var item in ViewBag.RolesList)
    {
        <tr>
            <td>
                @item
            </td>
        </tr>
    }
</table>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

 

The GroupsAdmin Delete.cshtml View:
@model IdentitySample.Models.ApplicationGroup
  
@{
    ViewBag.Title = "Delete";
}
  
<h2>Delete</h2>
  
<h3>Are you sure you want to delete this?</h3>
<div>
    <h4>ApplicationGroup</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Name)
        </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>

 

Updating the UserAdmin Views

We need to make a few minor changes to the UserAdmin Views. In the existing project, the UserAdmin Create and Edit Views allow us to assign Roles to the user. Instead, we want to assign the User to one or more Groups. Update the Create and Edit Views as follows:

Pay close attention when modifying the view code, and the names of Viewbag properties matter. 

The Modified UserAdmin Create.cshtml View:
@model IdentitySample.Models.RegisterViewModel
@{
    ViewBag.Title = "Create";
}
  
<h2>@ViewBag.Title.</h2>
  
@using (Html.BeginForm("Create", "UsersAdmin", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary("", new { @class = "text-error" })
    <div class="form-group">
        @Html.LabelFor(m => m.Email, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.Password, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.Password, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(m => m.ConfirmPassword, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.PasswordFor(m => m.ConfirmPassword, new { @class = "form-control" })
        </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">
            Select User Groups
        </label>
        <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.GroupsList)
            {
                <div>
                    <input type="checkbox" name="selectedGroups" value="@item.Value" class="checkbox-inline" />
                    @Html.Label(item.Text, new { @class = "control-label" })
                </div>
            }
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" class="btn btn-default" value="Create" />
        </div>
    </div>
}
  
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

 

The highlighted area calls out the primary impacted code.

Next, we will similarly modify the UsersAdmin => Edit.cshtml file.

The Modified UsersAdmin Edit.cshtml View:
@model IdentitySample.Models.EditUserViewModel
  
@{
    ViewBag.Title = "Edit";
}
  
<h2>Edit.</h2>
  
  
@using (Html.BeginForm()) {
    @Html.AntiForgeryToken()
  
    <div class="form-horizontal">
        <h4>Edit User Form.</h4>
        <hr />
        @Html.ValidationSummary(true)
        @Html.HiddenFor(model => model.Id)
  
        <div class="form-group">
            @Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
               @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })
               @Html.ValidationMessageFor(model => model.Email)
            </div>
        </div>
        <div class="form-group">
            @Html.Label("This User belongs to the following Groups", new { @class = "control-label col-md-2" })
            <span class=" col-md-10">
                @foreach (var item in Model.GroupsList)
                {
                    <div>
                        <input type="checkbox" name="selectedGroups" value="@item.Value" checked="@item.Selected" class="checkbox-inline" />
                        @Html.Label(item.Text, new { @class = "control-label" })
                    </div>
                }
            </span>
        </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 UsersAdmin Details.cshtml View displays a list of Roles assigned to the currently selected User. We will instead display a list of Groups:

The Modified UsersAdmin Details.cshtml View:
@model IdentitySample.Models.ApplicationUser
@{
    ViewBag.Title = "Details";
}
  
<h2>Details.</h2>
  
<div>
    <h4>User</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.UserName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.UserName)
        </dd>
    </dl>
</div>
<h4>List ofGroups this user belongs to:</h4>
@if (ViewBag.GroupNames.Count == 0)
{
    <hr />
    <p>No Groups found for this user.</p>
}
  
<table class="table">
    @foreach (var item in ViewBag.GroupNames)
    {
        <tr>
            <td>
                @item
            </td>
        </tr>
    }
</table>
<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

 

Of course, there is more we could do with the Views in this project, and we could add a few more for displaying User effective permissions (the sum permissions a user holds by virtue of membership in the assigned Groups) for example. For now, though, we'll just get things working, and then you can fine-tune things to the needs of your project.

Modify the Identity.Config File and the DbInitializer

In the previous project, when we set up Group-Based Permissions Management under Identity 1.0, we used EF Migrations to perform the database creation and Code-First generation. This time around, we are going to continue using the DbInitializer from the IdentitySamples project.

The ApplicationDbInitializer is defined in App_Start => IdentityConfig.cs. I have set it up for development purposes to inherit from DropCreateDatabaseAlways. However, you can easily change this to DropCreateDatabaseIfModelChanges.

Of course, we want our application to run with a basic configuration ready to go. Currently, the DbInitializer sets things up by creating a default User, an Admin Role, and then assigns the default user to that role.

We want to create the same default user, but then also create a default group. Then, we will create the default Admin role and assign it to the default group. Finally, we'll add the user to that group.

Open the App_Start => Identity.Config file, and make the following changes to the InitializeIdentityForEF() Method in the ApplicationDbInitializer class:

The InitializeIdentityForEF Method:
public static void InitializeIdentityForEF(ApplicationDbContext db) {
    var userManager = HttpContext.Current
        .GetOwinContext().GetUserManager<ApplicationUserManager>();
    var roleManager = HttpContext.Current
        .GetOwinContext().Get<ApplicationRoleManager>();
    const string name = "admin@example.com";
    const string password = "Admin@123456";
    const string roleName = "Admin";
  
    //Create Role Admin if it does not exist
    var role = roleManager.FindByName(roleName);
    if (role == null) {
        role = new ApplicationRole(roleName);
        var roleresult = roleManager.Create(role);
    }
  
    var user = userManager.FindByName(name);
    if (user == null) {
        user = new ApplicationUser 
        { 
            UserName = name, 
            Email = name, 
            EmailConfirmed = true
        };
        var result = userManager.Create(user, password);
        result = userManager.SetLockoutEnabled(user.Id, false);
    }
  
    var groupManager = new ApplicationGroupManager();
    var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All");
  
    groupManager.CreateGroup(newGroup);
    groupManager.SetUserGroups(user.Id, new string[] { newGroup.Id });
    groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
}

 

With that, we should be ready to run the application.

Running the Application

Once we've started the application and logged in, we should be able to navigate through the various admin functions. To make things interesting, let's add a few Roles, Groups, and Users and see what's what:

If we have added some additional Roles, Users, and Groups, we begin to see how this might work in the context of a real-world application. Lets take two fictitious departments, Sales and Purchasing. We might have some Roles at a relatively granular level (perhaps, at the level of our basic controller Actions) for each function:

Basic Roles for Sales and Purchasing Departments

sales-purchasing-roles

Now, this, and our other views could most likely use some help from a designer, or at least some presentation controls which would allow for better groupings, or something. Nonetheless, we see we have added some Roles here which correspond roughly with hypothetical controller actions we might find on a CustomersController and a ProductsController (OK - we're simplifying a little for the purpose of this example, but you get the idea).

Now, we might also define some Groups:

Basic Groups for Sales and Purchasing:

sales-purchasing-groups

Again, if we were worried about design aesthetics here, we might find our Groups management View a little lacking. But you can see that we have defined a few Groups related to the functions of the Sales and Purchasing departments.

Now, if we edit one of these groups, we can assign the appropriate Roles to the group:

Assigning Group Roles When Editing Group:

select-roles-for-group

Here, we have decided that users in the SalesAdmin Group should be able to add/edit/view/delete Customer data, as well as view (but not modify) product data.

Again, we might add some improvements to the display and grouping of the available roles here, but this works for demonstration purposes.

Now, if we save the SalesAdmin Group like this, we can then assign one or more users, who will then get all of the permissions associated with this group.

Creating a New User with Group Assignments:

create-user-with-group-assignments

Once we save, Jim will be a member of the SalesAdmin Group, and will have all of the Role permissions we assigned to that group.

Controlling Access with the [Authorize] Attribute

Of course, none of this does us any good if we don't put these granular Role permissions to use.

First off, we probably want to add some access control to our GroupsAdminController itself. We might want to add an [Authorize] decoration to the entire controller, similar to the UserAdminController, so that only those with the Admin Role can modify Groups.

Beyond that, though, let's expand upon our example above. Consider a hypothetical CustomersController. We might decorate the basic controller methods as follows, in keeping with the Roles we defined:

Hypothetical CustomersController:
public class CustomerController
{
    [Authorize(Roles = "CanViewCustomers")]
    public async ActionResult Index()
    {
        // Code...
    }
  
  
    [Authorize(Roles = "CanAddCustomers")]
    public async ActionResult Create()
    {
        // Code...
    }
  
  
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "CanAddCustomers")]
    public async Task<ActionResult> Create(SomeArguments)
    {
        // Code...
    }
  
  
    [Authorize(Roles = "CanEditCustomers")]
    public async ActionResult Edit(int id)
    {
        // Code...
    }
  
  
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "CanEditCustomers")]
    public async Task<ActionResult> Edit(SomeArguments)
    {
        // Code...
    }
  
  
    [Authorize(Roles = "CanDeleteCustomers")]
    public async Task<ActionResult> Delete(id)
    {
        // Code...
    }
  
  
    [HttpPost]
    [ValidateAntiForgeryToken]
    [Authorize(Roles = "CanDeleteCustomers")]
    public async Task<ActionResult> Delete(SomeArguments)
    {
        // Code...
    }
}

 

We can see that we have now implemented some authorization control which corresponds to some of the Roles we defined. The roles themselves are not specific to any one type of user. instead, Roles can be assigned to different Groups. From there, it is a simple matter to add or remove users from one or more groups, depending upon their function and access requirements.

Some Thoughts on Authorization and Security

The concepts in this project are sort of a middle ground between the basic, but highly functional authorization mechanism offered by Identity 2.0 out of the box, and more complex implementations using Claims or Active Directory.

The system illustrated here will afford a more granular control over Roles and Authorization to access and execute code. However, there is a practical limit.

Designing a robust application authorization matrix requires careful thought, and choosing the correct tools (as with most things in development). Planning carefully upfront will go a long ways towards helping you create a solid, maintainable application.

If you get too fine-grained in your Authorizations and Role definitions, you will have a difficult to manage mess. Not going granular enough results in a clunky, limited authorization scheme where you may find yourself giving users too much or too little access.

Errata, Ideas, and Pull Requests

It is entirely possible I have missed something in putting the code together for this article. Also, as noted, there is plenty of room for improvement in the design here. If you find something broken, have an idea to improve the concept, or (Especially) would like to improve the Views with respect to organizing Roles, Groups, etc, please open an issue or send me a Pull Request.

Additional Resources and Items of Interest

 

Posted on August 10 2014 07:35 PM by jatten     

Comments (4)

ASP.NET Identity 2.0 Extending Identity Models and Using Integer Keys Instead of Strings

Posted on July 13 2014 10:45 AM by jatten in ASP.NET MVC, ASP.Net, C#, CodeProject   ||   Comments (20)

Identity-240The ASP.NET Identity framework was released to manufacture on March 20 2014, bringing with it a slew of long-awaited enhancements, delivering a fully-formed authentication and authorization platform to the ASP.NET developer community.

In previous posts, we have taken a broad look at the structure of the new framework, and how it differs from the 1.0 release. We've also walked through implementing email account confirmation and two-factor authentication, as well as extending the basic User and Role models (which requires a bit more effort than you might think).

Image by Josh Cowper  | Some Rights Reserved

In this post we're going take a deeper look at extending the core set of models afforded by the Identity 2.0 framework, and re-implementing the basic Identity Samples project using integer keys for all of our models, instead of the default string keys which are the default.

Source Code on Github

In the course of this article, we will basically re-implement the Identity Samples project with integer keys. you can clone the completed source code from my Github repo. Also, if you find bugs and/or have suggestions, please do open an issue and/or shoot me a pull request!

Why Does ASP.NET Identity Use String Keys in the First Place?

A popular, and somewhat confounding question is "why did the Identity team choose string keys as the default for the Identity framework models? Many of us who grew up using databases tend towards easy, auto-incrementing integers as database primary keys, because it's easy, and at least in theory, there are some performance advantages with respect to table indexes and such.

The decision of the Identity Team to use strings as keys is best summarized in a Stack Overflow answer by Rick Anderson, writer for ASP.NET at Microsoft:

  1. The Identity runtime prefers strings for the user ID because we don’t want to be in the business of figuring out proper serialization of the user IDs (we use strings for claims as well for the same reason), e.g. all (or most) of the Identity interfaces refer to user ID as a string.
  2. People that customize the persistence layer, e.g. the entity types, can choose whatever type they want for keys, but then they own providing us with a string representation of the keys.
  3. By default we use the string representation of GUIDs for each new user, but that is just because it provides a very easy way for us to automatically generate unique IDs.

The decision is not without its detractors in the community. The default string key described above is essentially a string representation of a Guid. As this discussion on Reddit illustrates, there is contention about the performance aspects of this against a relational database backend.

The concerns noted in the Reddit discussion focus mainly on database index performance, and are unlikely to be an issue for a large number of smaller sites and web applications, and particularly for learning projects and students. However, as noted previously, for many of us, the auto-incrementing integer is the database primary key of choice (even in cases where it is not the BEST choice), and we want our web application to follow suit.

Identity 2.0 Core Classes use Generic Type Arguments

As we discussed in the post on customizing ASP.NET Identity 2.0 Users and Roles, the framework is built up from a structure of generic Interfaces and base classes. At the lowest level, we find interfaces, such as IUser<TKey> and IRole<TKey>. These, and related Interfaces and base classes are defined in the Microsoft.AspNet.Identity.Core library.

Moving up a level of abstraction, we can look at the Microsoft.AspNet.Identity.EntityFramework library, which uses the components defined in …Identity.Core to build the useful, ready-to-use classes commonly used in applications, and in particular by the Identity Samples project we have been using to explore Identity 2.0.

The Identity.EntityFramework library gives us some Generic base classes, as well as a default concrete implementation for each. For example, Identity.EntityFramework gives us the following generic base implementation for a class IdentityRole:

Generic Base for IdentityRole:
public class IdentityRole<TKey, TUserRole> : IRole<TKey>
where TUserRole : IdentityUserRole<TKey>
{
    public TKey Id { get; set; }
    public string Name { get; set; }
    public ICollection<TUserRole> Users { get; set; }
    public IdentityRole()
    {
        this.Users = new List<TUserRole>();
    }
}

 

As we can see, the above defines IdentityRole in terms of generic type arguments for the key and UserRole, and must implement the interface IRole<TKey>. Note that Identity defines both an IdentityRole class, as well as an IdentityUserRole class, both of which are required to make things work. More on this later.

The Identity team also provides what amounts to a default implementation of this class:

Default Implementation of IdentityRole with non-generic type arguments:
public class IdentityRole : IdentityRole<string, IdentityUserRole>
{
    public IdentityRole()
    {
        base.Id = Guid.NewGuid().ToString();
    }
  
  
    public IdentityRole(string roleName) : this()
    {
        base.Name = roleName;
    }
}

 

Notice how the default implementation class is defined in terms of a string key and a specific implementation of IdentityUserRole?

This means that we can only pass strings as keys, and in fact the IdentityRole model will be defined in our database with a string-type primary key. It also means that the specific, non-generic implementation of IdentityUserRole will be what is passed to the type argument into the base class.

If we steal a page from the previous post, and take a look at the default type definitions provided by Identity 2.0, we find the following (it's not exhaustive, but these are what we will be dealing with later):

Default Identity 2.0 Class Signatures with Default Type Arguments:
public class IdentityUserRole 
    : IdentityUserRole<string>
  
public class IdentityRole 
    : IdentityRole<string, IdentityUserRole>
  
public class IdentityUserClaim 
    : IdentityUserClaim<string>
  
public class IdentityUserLogin 
    : IdentityUserLogin<string>
  
public class IdentityUser 
    : IdentityUser<string, IdentityUserLogin, 
        IdentityUserRole, IdentityUserClaim>, IUser, IUser<string>
  
public class IdentityDbContext 
    : IdentityDbContext<IdentityUser, IdentityRole, string, 
        IdentityUserLogin, IdentityUserRole, IdentityUserClaim>
  
public class UserStore<TUser> 
    : UserStore<TUser, IdentityRole, string, IdentityUserLogin, 
        IdentityUserRole, IdentityUserClaim>, 
        IUserStore<TUser>, IUserStore<TUser, string>, IDisposable
    where TUser : IdentityUser
  
public class RoleStore<TRole> 
    : RoleStore<TRole, string, IdentityUserRole>, IQueryableRoleStore<TRole>, 
        IQueryableRoleStore<TRole, string>, IRoleStore<TRole, string>, IDisposable
    where TRole : IdentityRole, new()

 

We can see that, starting with IdentityUserRole, the types are defined with string keys, and as importantly, progressively defined in terms of the others. This means that if we want to use integer keys instead of string keys for all of our models (and corresponding database tables), we need to basically implement our own version of the stack above.

Implementing Integer Keys Using Identity 2.0 and the Identity Samples Project

As in previous posts, we are going to use the Identity Samples project as our base for creating an Identity 2.0 MVC application. The Identity team has put together the Identity Samples project primarily (I assume) as a demonstration platform, but in fact it contains everything one might need (after a few tweaks, anyway) in order to build out a complete ASP.NET MVC project using the Identity 2.0 framework.

The concepts we are going to look at here apply equally well if you are building up your own Identity-based application from scratch. The ways and means might vary according to your needs, but in general, much of what we see here will apply whether you are starting from the Identity Samples project as a base, or "rolling your own" so to speak.

The important thing to bear in mind is that the generic base types and interfaces provided by Identity framework allow great flexibility, but also introduced complexity related to the dependencies introduced by the generic type arguments. In particular, the type specified as the key for each model must propagate through the stack, or the compiler gets angry.

Getting Started - Installing the Identity Samples Project

The Identity Samples project is available on Nuget. First, create an empty ASP.NET Web Project (It is important that you use the "Empty" template here, not MVC, not Webforms, EMPTY). Then open the Package Manager console and type:

Install Identity Samples from the Package Manager Console:
PM> Install-Package Microsoft.AspNet.Identity.Samples -Pre

 

This may take a minute or two to run. When complete, your will see a basic ASP.NET MVC project in the VS Solution Explorer. Take a good look around the Identity 2.0 Samples project, and become familiar with what things are and where they are at.

Re-Engineering the Basic Identity Models

To get started, we need to re-engineer the basic model classes defined in the Identity Samples project, as well as add a few new ones. Because Identity Samples uses string-based keys for entity models, the authors, in many cases get away with depending upon the default class implementations provided by the framework itself. Where they extend, they extend from the default classes, meaning the string-based keys are still baked in to the derived classes.

Since we want to use integer keys for all of our models, we get to provide our own implementations for most of the models.

In many cases, this isn't as bad as it sounds. For example, there are a handful of model classes we need only define in terms of the generic arguments, and from there the base class implementation does the rest of the work.

NOTE: As we proceed to modify/add new classes here, the error list in Visual Studio will begin to light up like a Christmas tree until we are done. Leave that be for the moment. If we do this correctly, there should be no errors left when we finish. IF there are, they will help us find things we missed.

In the Models => IdentityModels.cs file, we find the model classes used by the Identity Samples application. To get started, we are going to add our own definitions for IndentityUserLogin, IdentityUserClaim, and IdentityUserRole. The Identity Samples project simply depended upon the default framework implementations for these classes, and we need our own integer based versions. Add the following to the IdentityModels.cs file:

Integer-Based Definitions for UserLogin, UserClaim, and UserRole:
public class ApplicationUserLogin : IdentityUserLogin<int> { }
public class ApplicationUserClaim : IdentityUserClaim<int> { }
public class ApplicationUserRole : IdentityUserRole<int> { }

 

Now, with that out of the way, we can define our own implementation of IdentityRole. The Samples project also depended upon the framework version for IdentityRole, and we are going to provide our own again. This time, though, there's a little more to it:

Integer-Based Definition for IdentityRole:
public class ApplicationRole : IdentityRole<int, ApplicationUserRole>, IRole<int>
{
    public string Description { get; set; }
  
    public ApplicationRole() { }
    public ApplicationRole(string name)
        : this()
    {
        this.Name = name;
    }
  
    public ApplicationRole(string name, string description)
        : this(name)
    {
        this.Description = description;
    }
}

 

Notice above, we have defined ApplicationRole in terms of an integer key, and also in terms of our custom class ApplicationUserRole? This is important, and will continue on up the stack as we re-implement the Identity classes we need for the Identity Samples project to run as expected.

Next, we are going to modify the existing definition for ApplicationUser. Currently, the IdentitySamples.cs file includes a fairly simple definition for ApplicationUser which derives from the default IdentityUser class provided by the framework, which requires no type arguments because they have already been provided in the default implementation. We need to basically re-define ApplicationUser starting from the ground up.

The existing ApplicationUser class in the IdentityModels.cs file looks like this:

Existing ApplicationUser Class in IdentityModels.cs:
public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> 
        GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager
            .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

 

We need to replace the above in its entirety with the following:

Custom Implementation for ApplicationUser:
public class ApplicationUser 
: IdentityUser<int, ApplicationUserLogin, 
    ApplicationUserRole, ApplicationUserClaim>, IUser<int>
{
    public async Task<ClaimsIdentity>
        GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
    {
        var userIdentity = await manager
            .CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
}

 

Once again, instead of deriving from the default Identity framework implementation for IdentityUser, we have instead used the generic base, and provided our own custom type arguments. Also again, we have defined our custom ApplicationUser in terms of an integer key, and our own custom types.

Modified Application Db Context

Also in the IdentityModels.cs file is an ApplicationDbContext class.

Now that we have built out the basic models we are going to need, we also need to re-define the ApplicationDbContext in terms of these new models. As previously, the existing ApplicationDbContext used in the Identity Samples application is expressed only in terms of ApplicationUser, relying (again) upon the default concrete implementation provided by the framework.

If we look under the covers, we find the ApplicationDbContext<ApplicationUser> actually inherits from IdentityDbContext<ApplicationUser>, which in turn is derived from:

IdentityDbContext<TUser, IdentityRole, string, IdentityUserLogin,
    IdentityUserRole, IdentityUserClaim>
    where TUser : Microsoft.AspNet.Identity.EntityFramework.IdentityUser

In other words, we once again have a default concrete implementation which is defined in terms of the other default framework types, all of which further depend upon a string-based key.

In order to define a DbContext which will work with our new custom types, we need to express our concrete class in terms of integer keys, and our own custom derived types.

Replace the existing ApplicationDbContext code with the following:

Modified ApplicationDbContext:
public class ApplicationDbContext 
    : IdentityDbContext<ApplicationUser, ApplicationRole, int, 
    ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }
  
    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }
  
    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

 

Once again, we have now expressed ApplicationDbContext in terms of our own custom types, all of which use an integer key instead of a string.

Custom User and Role Stores

I am willing to bet that if you take a look at the Visual Studio Error Window right now, it is likely a block of what seems to be endless red error indicators. As mentioned previously, that's fine for now - ignore it.

Identity framework defines the notion of User and Role stores for accessing user and role information. As with most everything else to this point, the default framework implementations for UserStore and RoleStore are defined in terms of the other default classes we have seen to this point - in other words, they won't work with our new custom classes. We need to express a custom User store, and a custom Role store, in terms of integer keys and our own custom classes.

Add the following to the IdentityModels.cs file:

Adding a Custom User Store:
    public class ApplicationUserStore : 
        UserStore<ApplicationUser, ApplicationRole, int,
        ApplicationUserLogin, ApplicationUserRole, 
        ApplicationUserClaim>, IUserStore<ApplicationUser, int>, 
        IDisposable
    {
        public ApplicationUserStore() : this(new IdentityDbContext())
        {
            base.DisposeContext = true;
        }
  
        public ApplicationUserStore(DbContext context)
            : base(context)
        {
        }
    }
  
  
    public class ApplicationRoleStore 
        : RoleStore<ApplicationRole, int, ApplicationUserRole>, 
        IQueryableRoleStore<ApplicationRole, int>, 
        IRoleStore<ApplicationRole, int>, IDisposable
    {
        public ApplicationRoleStore()
            : base(new IdentityDbContext())
        {
            base.DisposeContext = true;
        }
  
        public ApplicationRoleStore(DbContext context)
            : base(context)
        {
        }
    }

 

Re-Engineering Identity Configuration Classes

The Identity Samples project includes a file named App_Start => IdentityConfig.cs. In this file is a bunch of code which basically configures the Identity System for use in your application. The changes we introduced on our IdentityModels.cs file will cause issues here (and basically, throughout the application) until they are addressed in the client code.

In most cases, we will either be replacing a reference to a default Identity class with one of our new custom classes, and/or calling method overrides which allow the passing of custom type arguments.

In the IdentityConfig.cs file, we find an ApplicationUserManager class, which contains code commonly called by our application to, well, manage users and behaviors. we will replace the existing code with the following, which essentially expresses ApplicationUserManager in terms of integer keys, and our new custom UserStore. If you look closely, we have added an int type argument to many of the method calls.

Customized ApplicationUserManager Class:
// *** PASS IN TYPE ARGUMENT TO BASE CLASS:
public class ApplicationUserManager : UserManager<ApplicationUser, int>
{
    // *** ADD INT TYPE ARGUMENT TO CONSTRUCTOR CALL:
    public ApplicationUserManager(IUserStore<ApplicationUser, int> store)
        : base(store)
    {
    }
  
    public static ApplicationUserManager Create(
        IdentityFactoryOptions<ApplicationUserManager> options,
        IOwinContext context)
    {
        // *** PASS CUSTOM APPLICATION USER STORE AS CONSTRUCTOR ARGUMENT:
        var manager = new ApplicationUserManager(
            new ApplicationUserStore(context.Get<ApplicationDbContext>()));
  
        // Configure validation logic for usernames
  
        // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
        manager.UserValidator = new UserValidator<ApplicationUser, int>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
  
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
  
        // Configure user lockout defaults
        manager.UserLockoutEnabledByDefault = true;
        manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
        manager.MaxFailedAccessAttemptsBeforeLockout = 5;
   
        // Register two factor authentication providers. 
        // This application uses Phone and Emails as a step of receiving a 
        // code for verifying the user You can write your own provider and plug in here.
  
        // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
        manager.RegisterTwoFactorProvider("PhoneCode", 
            new PhoneNumberTokenProvider<ApplicationUser, int>
        {
            MessageFormat = "Your security code is: {0}"
        });
  
          // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
        manager.RegisterTwoFactorProvider("EmailCode", 
            new EmailTokenProvider<ApplicationUser, int>
        {
            Subject = "SecurityCode",
            BodyFormat = "Your security code is {0}"
        });
  
        manager.EmailService = new EmailService();
        manager.SmsService = new SmsService();
        var dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            // *** ADD INT TYPE ARGUMENT TO METHOD CALL:
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser, int>(
                    dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}

 

That's a lot of code there. Fortunately, modifying the ApplicationRoleManager class is not such a big deal. We're essentially doing the same thing - expressing ApplicationRoleManager in terms of integer type arguments, and our custom classes.

Replace the ApplicationRoleManager code with the following:

Customized ApplicationRoleManager Class:
// PASS CUSTOM APPLICATION ROLE AND INT AS TYPE ARGUMENTS TO BASE:
public class ApplicationRoleManager : RoleManager<ApplicationRole, int>
{
    // PASS CUSTOM APPLICATION ROLE AND INT AS TYPE ARGUMENTS TO CONSTRUCTOR:
    public ApplicationRoleManager(IRoleStore<ApplicationRole, int> roleStore)
        : base(roleStore)
    {
    }
  
    // PASS CUSTOM APPLICATION ROLE AS TYPE ARGUMENT:
    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(
            new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
    }
}

 

Modify The Application Database Initializer and Sign-in Manager

The ApplicationDbInitializer class is what manages the creation and seeding of the backing database for our application. In this class we create a basic admin role user, and set up additional items such as the Email and SMS messaging providers.

The only thing we need to change here is where we initialize an instance of ApplicationRole. In the existing code, the ApplicationDbInitializer class instantiates an instance of IdentityRole, and we need to create an instance of our own ApplicationRole instead.

Replace the existing code with the following, or make the change highlighted below:

Modify the ApplicationDbInitializer Class:
public class ApplicationDbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> 
{
    protected override void Seed(ApplicationDbContext context) {
        InitializeIdentityForEF(context);
        base.Seed(context);
    }
  
    //Create User=Admin@Admin.com with password=Admin@123456 in the Admin role        
    public static void InitializeIdentityForEF(ApplicationDbContext db) {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
        const string name = "admin@example.com";
        const string password = "Admin@123456";
        const string roleName = "Admin";
  
        //Create Role Admin if it does not exist
        var role = roleManager.FindByName(roleName);
        if (role == null) {
            // *** INITIALIZE WITH CUSTOM APPLICATION ROLE CLASS:
            role = new ApplicationRole(roleName);
            var roleresult = roleManager.Create(role);
        }
  
        var user = userManager.FindByName(name);
        if (user == null) {
            user = new ApplicationUser { UserName = name, Email = name };
            var result = userManager.Create(user, password);
            result = userManager.SetLockoutEnabled(user.Id, false);
        }
  
        // Add user admin to Role Admin if not already added
        var rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name)) {
            var result = userManager.AddToRole(user.Id, role.Name);
        }
    }
}

 

Fixing up the ApplicationSignInManager is even more simple. Just change the string type argument in the class declaration to int:

Modify the ApplicationSignInManager Class:
// PASS INT AS TYPE ARGUMENT TO BASE INSTEAD OF STRING:
public class ApplicationSignInManager : SignInManager<ApplicationUser, int>
{
    public ApplicationSignInManager(
        ApplicationUserManager userManager, IAuthenticationManager authenticationManager) : 
        base(userManager, authenticationManager) { }
  
    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }
  
    public static ApplicationSignInManager Create(
     IdentityFactoryOptions<ApplicationSignInManager> options, IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), context.Authentication);
    }
}

 

Cookie Authentication Configuration

In the file App_Start => Startup.Auth there is a partial class definition, Startup. in the single method call defined in the partial class, there is a call to app.UseCookieAuthentication(). Now that our application is using integers as keys instead of strings, we need to make a modification to the way the CookieAuthenticationProvider is instantiated.

The existing call to app.UseCookieAuthentication (found smack in the middle of the middle of the ConfigureAuth() method) needs to be modified. Where the code calls OnVlidateIdentity the existing code passes ApplicationUserManager and ApplicationUser as type arguments. What is not obvious is that this is an override which assumes a third, string type argument for the key (yep - we're back to that whole string keys thing again).

We need to change this code to call another override, which accepts a third type argument, and pass it an int argument.

The existing code looks like this:

Existing Call to app.UseCookieAuthentication:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a 
        // password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator
            .OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                validateInterval: TimeSpan.FromMinutes(30),
                regenerateIdentity: (manager, user) 
                    => user.GenerateUserIdentityAsync(manager))
    }
});

 

We need to modify this code in a couple of non-obvious ways. First, as mentioned above, we need to add a third type argument specifying that TKey is an int.

Less obvious is that we also need to change the name of the second argument from regenerateIdentity to regenerateIdentityCallback. Same argument, but different name in the overload we are using.

Also less than obvious is the third Func we need to pass into the call as getUserIdCallback. Here, we need to retreive a user id from a claim, which stored the Id as a string. We need to parse the result back into an int.

Replace the existing code above with the following:

Modified Call to app.UseCookieAuthentication:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a 
        // password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator
            // ADD AN INT AS A THIRD TYPE ARGUMENT:
            .OnValidateIdentity<ApplicationUserManager, ApplicationUser, int>(
                validateInterval: TimeSpan.FromMinutes(30),
                // THE NAMED ARGUMENT IS DIFFERENT:
                regenerateIdentityCallback: (manager, user) 
                    => user.GenerateUserIdentityAsync(manager),
                    // Need to add THIS line because we added the third type argument (int) above:
                    getUserIdCallback:  (claim) => int.Parse(claim.GetUserId()))
    }
});

 

With that, most of the Identity infrastructure is in place. Now we need to update a few things within our application.

Update Admin View Models

The Models => AdminViewModels.cs file contains  class definitions for a RolesAdminViewModel and a UsersAdminViewModel. In both cases, we need to change the type of the Id property from string to int:

Modify the Admin View Models:
public class RoleViewModel
{
    // Change the Id type from string to int:
    public int Id { get; set; }
    
    [Required(AllowEmptyStrings = false)]
    [Display(Name = "RoleName")]
    public string Name { get; set; }
}
  
public class EditUserViewModel
{
    // Change the Id Type from string to int:
    public int Id { get; set; }
  
    [Required(AllowEmptyStrings = false)]
    [Display(Name = "Email")]
    [EmailAddress]
    public string Email { get; set; }
  
    public IEnumerable<SelectListItem> RolesList { get; set; }
}

 

Update Controller Method Parameter Arguments

A good many of the controller action methods currently expect an id argument of type string. We need to go through all of the methods in our controllers and change the type of the id argument from string to int.

In each of the following controllers, we need to change the existing Id from string to int as shown for the action methods indicated (we're only showing the modified method signatures here):

Account Controller:
public async Task<ActionResult> ConfirmEmail(int userId, string code)

 

Roles Admin Controller:
public async Task<ActionResult> Edit(int id)
public async Task<ActionResult> Details(int id)
public async Task<ActionResult> Delete(int id)
public async Task<ActionResult> DeleteConfirmed(int id, string deleteUser)

 

Users Admin Controller:
public async Task<ActionResult> Details(int id)
public async Task<ActionResult> Edit(int id)
public async Task<ActionResult> Delete(int id)
public async Task<ActionResult> DeleteConfirmed(int id)

 

Update the Create Method on Roles Admin Controller

Anywhere we are creating a new instance of a Role, we need to make sure we are using our new ApplicationRole instead of the default IdentityRole. Specifically, in the Create() method of the RolesAdminController:

Instantiate a new ApplicationRole Instead of IdentityRole:
[HttpPost]
public async Task<ActionResult> Create(RoleViewModel roleViewModel)
{
    if (ModelState.IsValid)
    {
        // Use ApplicationRole, not IdentityRole:
        var role = new ApplicationRole(roleViewModel.Name);
        var roleresult = await RoleManager.CreateAsync(role);
        if (!roleresult.Succeeded)
        {
            ModelState.AddModelError("", roleresult.Errors.First());
            return View();
        }
        return RedirectToAction("Index");
    }
    return View();
}

 

Add Integer Type Argument to GetUserId() Calls

If we take a look at our Error list now, we see the preponderance of errors are related to calls to User.Identity.GetUserId(). If we take a closer look at this method, we find that once again, the default version of GetUserId() returns a string, and that there is an overload which accepts a type argument which determines the return type.

Sadly, calls to GetUserId() are sprinkled liberally throughout ManageController, and a few places in AccountController as well. We need to change all of the calls to reflect the proper type argument, and the most efficient way to do this is an old fashioned Find/Replace.

Fortunately, you can use Find/Replace for the entire document on both ManageController and AccountController, and get the whole thing done in one fell swoop. Hit Ctrl + H, and in the "Find" box, enter the following:

Find all instances of:
Identity.GetUserId()

 

Replace with:
Identity.GetUserId<int>()

 

If we've done this properly, most of the glaring red errors in our error list should now be gone. There are a few stragglers, though. In these cases, we need to counter-intuitively convert the int Id back into a string.

Return a String Where Required

There are a handful of methods which call to GetUserId(), but regardless of the type the Id represents (in our case, now, an int) want a string representation of the Id passed as the argument. All of these methods are found on ManageController, and in each case, we just add a call to .ToString().

First, in the Index() method of ManageController, we find a call to AuthenticationManager.TwoFactorBrowserRemembered() . Add the call to .ToString() after the call to GetUserId():

Add Call to ToString() to TwoFactorBrowserRemembered:
public async Task<ActionResult> Index(ManageMessageId? message)
{
    ViewBag.StatusMessage =
        message == ManageMessageId.ChangePasswordSuccess ? 
            "Your password has been changed."
        : message == ManageMessageId.SetPasswordSuccess ? 
            "Your password has been set."
        : message == ManageMessageId.SetTwoFactorSuccess ? 
            "Your two factor provider has been set."
        : message == ManageMessageId.Error ? 
            "An error has occurred."
        : message == ManageMessageId.AddPhoneSuccess ? 
            "The phone number was added."
        : message == ManageMessageId.RemovePhoneSuccess ? 
            "Your phone number was removed."
        : "";
  
    var model = new IndexViewModel
    {
        HasPassword = HasPassword(),
        PhoneNumber = await UserManager.GetPhoneNumberAsync(User.Identity.GetUserId<int>()),
        TwoFactor = await UserManager.GetTwoFactorEnabledAsync(User.Identity.GetUserId<int>()),
        Logins = await UserManager.GetLoginsAsync(User.Identity.GetUserId<int>()),
  
        // *** Add .ToString() to call to GetUserId():
        BrowserRemembered = await AuthenticationManager
            .TwoFactorBrowserRememberedAsync(User.Identity.GetUserId<int>().ToString())
    };
    return View(model);
}

 

Similarly, do the same for the RememberBrowser method, also on ManageController:

Add Call to ToString() to RememberBrowser Method:
[HttpPost]
public ActionResult RememberBrowser()
{
    var rememberBrowserIdentity = AuthenticationManager
        .CreateTwoFactorRememberBrowserIdentity(
            // *** Add .ToString() to call to GetUserId():
            User.Identity.GetUserId<int>().ToString());
    AuthenticationManager.SignIn(
        new AuthenticationProperties { IsPersistent = true }, 
        rememberBrowserIdentity);
    return RedirectToAction("Index", "Manage");
}

 

Lastly,the same for the LinkLogin() and LinkLoginCallback() methods:

Add Call to ToString() to LinkLogin():
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LinkLogin(string provider)
{
    return new AccountController
        .ChallengeResult(provider, Url.Action("LinkLoginCallback", "Manage"), 
            // *** Add .ToString() to call to GetUserId():
            User.Identity.GetUserId<int>().ToString());
}

 

Add Call to ToString() to LinkLoginCallback():
public async Task<ActionResult> LinkLoginCallback()
{
    var loginInfo = await AuthenticationManager
        .GetExternalLoginInfoAsync(XsrfKey, User.Identity.GetUserId<int>().ToString());
    if (loginInfo == null)
    {
        return RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
    }
    var result = await UserManager
        // *** Add .ToString() to call to GetUserId():
        .AddLoginAsync(User.Identity.GetUserId<int>().ToString(), loginInfo.Login);
  
    return result.Succeeded ? RedirectToAction("ManageLogins") 
        : RedirectToAction("ManageLogins", new { Message = ManageMessageId.Error });
}

 

With that, we have addressed most of the egregious issues, and we basically taken a project built against a model set using all string keys and converted it to using integers. The integer types will be propagated as auto-incrementing integer primary keys in the database backend as well.

But there are still a few things to clean up.

Fix Null Checks Against Integer Types

Scattered throughout the primary identity controllers are a bunch of null checks against the Id values received as arguments in the method calls. If you rebuild the project, the error list window in Visual Studio should now contain a bunch of the yellow "warning" items about this very thing.

You can handle this in your preferred manner, but for me, I prefer to check for a positive integer value. We'll look at the Details() method from the UserAdminController as an example, and you can take it from there.

The existing code in the Details() method looks like this:

Existing Details() Method from UserAdminController:
public async Task<ActionResult> Details(int id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    var user = await UserManager.FindByIdAsync(id);
    ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
    return View(user);
}

 

In the above, we can see that previously, the code checked for a null value for the (formerly) string-typed Id argument. Now that we are receiving an int, the check for null is meaningless. Instead, we want to check for a positive integer value. If the check is true, then we want to process accordingly. Otherwise, we want to return the BadRequest result.

In other words, we need to invert the method logic. Previously, if the conditional evaluated to true, we wanted to return the error code. Now, is the result is true, we want to proceed, and only return the error result if the conditional is false. So we're going to swap our logic around.

Replace the code with the following:

Modified Details() Method with Inverted Conditional Logic:
public async Task<ActionResult> Details(int id)
{
    if (id > 0)
    {
        // Process normally:
        var user = await UserManager.FindByIdAsync(id);
        ViewBag.RoleNames = await UserManager.GetRolesAsync(user.Id);
        return View(user);
    }
    // Return Error:
    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

 

We can do something similar for the other cases in UserAdminController, RolesAdminController, and AccountController. Think through the logic carefully, and all should be well.

Update Roles Admin Views

Several of the View Templates currently use the default IdentityRole model instead of our new, custom ApplicationRole. We need to update the Views in Views => RolesAdmin to reflect our new custom model.

The Create.cshtml and Edit.cshtml Views both depend upon the RoleViewModel, which is fine. However, the Index.cshtml, Details.cshtml, and Delete.cshtml Views all currently refer to IdentityRole. Update all three as follows

The Index.cshtml View currently expects an IEnumerable<IdentityRole> . We need to change this to expect an IEnumerable<ApplicationRole> . Note that we need to include the project Models namespace as well:

Update the RolesAdmin Index.cshtml View:
@model IEnumerable<IdentitySample.Models.ApplicationRole>
// ... All the view code ...

 

All we need to change here is the first line, so I omitted the rest of the View code.

Similarly, we need to update the Details.cshtml and Delete.cshtml Views to expect ApplicationRole instead of IdentityRole. Change the first line in each to match the following:

Update the Details.cshtml and Delete.cshtml Views:
@model IdentitySample.Models.ApplicationRole
// ... All the view code ...

 

Obviously, if your default project namespace is something other than IdentitySamples, change the above to suit.

Additional Extensions are Easy Now

Now that we have essentially re-implemented most of the Identity object models with our own derived types, it is easy to add custom properties to the ApplicationUser and/.or ApplicationRole models. All of our custom types already depend upon each other in terms of the interrelated generic type arguments, so we are free to simply add what properties we wish to add, and then update our Controllers, ViewModels, and Views accordingly.

To do so, review the previous post on extending Users and Roles, but realize all of the type structure stuff is already done. Review that post just to see what goes on with updating the Controllers, Views, and ViewModels.

A Note on Security

The basic Identity Samples application is a great starting point for building out your own Identity 2.0 application. However, realize that, as a demo, there are some things built in that should not be present in production code. For example, the database initialization currently includes hard-coded admin user credentials.

Also, the Email confirmation and two-factor authentication functionality currently circumvents the actual confirmation and two-factor process, by including links on each respective page which short-circuit the process.

The above items should be addressed before deploying an actual application based upon the Identity Samples project.

Wrapping Up

We've taken a rather exhaustive look at how to modify the Identity Samples application to use integer keys instead of strings. Along the way, we (hopefully) gained a deeper understanding of the underlying structure in an Identity 2.0 based application. There's a lot more there to learn, but this is a good start.

Additional Resources and Items of Interest

 

Posted on July 13 2014 10:45 AM by jatten     

Comments (20)

Creating A Basic Make File for Compiling C Code

Posted on July 6 2014 02:30 PM by jatten in Linux, Education, CodeProject, Learning   ||   Comments (3)

binary-blanket-240I recently began taking a Harvard computer science course. As pretentious as that sounds, it's not as bad as it seems. I am taking Harvard CS50 on-line, for free, in an attempt to push my knowledge and expand my understanding of this thing I love so much, programming.

The course uses Linux and C as two of the primary learning tools/environments. While I am semi-capable using Linux, and the syntax of C is vary familiar, the mechanics of C compilation, linking, and makefiles are all new.

Image by quimby  |  Some Rights Reserved

If you are an experienced C developer, or if you have worked extensively with Make before, there is likely nothing new for you here. However, if you wanted to let me know if and when I am passing bad information, please do! This article will (hopefully) be helpful to those who are just getting started compiling C programs, and/or using the GNU Make utility.

In the post, we discuss some things that are specific to the context of the course exercises. However, the concepts discussed, and the examples introduced are general enough that the post should be useful beyond the course specifics.

The course makes available an "appliance" (basically, a pre-configured VM which includes all the required software and files), which I believe can be downloaded by anyone taking even the free on-line course. However, since I already know how to set up/configure a Linux box (but can always use extra practice), I figured my learning would be augmented by doing things the hard way, and doing everything the course requires manually.

For better or for worse, this has forced me to learn about Make and makefiles (this is for the better, I just opened the sentence that way to sound good).

Make File Examples on Github

In this post we will put together a handful of example Make files. You can also find them as source at my Github repo:

Compiling and Linking - The Simple

This is by no means a deeply considered resource on compiling and linking source code. However, in order to understand how make works, we need to understand compiling and linking at some level.

Let's consider the canonical "Hello World!" program, written in the C programming language. Say we have the following source file, suitably named hello.c:

Basic Hello World Implementation in C:
#include <stdio.h>
  
int main(void)
{
    printf("Hello, World!\n");
}

 

In the above, the first line instructs the compiler to include the C Standard IO library, by making reference to the stdio.h header file. This is followed by our application code, which impressively prints the string "Hello World!" to the terminal window.

In order to run the above, we need to compile first. Since the Harvard course is using the Clang compiler, the most basic compilation command we can enter from the terminal might be:

Basic Compile Command for Hello World:
$ clang hello.c -o hello

 

When we enter the above command in our terminal window, we are essentially telling the Clang compiler to compile the source file hello.c, and the -o flag tells it to name the output binary file hello.

This works well enough for a simple task like compiling Hello World. Files from the C Standard Library are linked automatically, and the only compiler flag we are using is -o to name the output file (if we didn't do this, the output file would be named a.out, the default output file name).

Compiling and Linking - A Little More Complex

When I say "Complex" in the header above, it's all relative. We will expand on our simple Hello World example by adding an external library, and using some additional important compiler flags.

The Harvard CS50 course staff created a cs50 library for use by students in the course. The library includes some functions to ease folks into working with C. Among other things, the staff have added a number of functions designed to retreive terminal input from the user. For example, the cs50 library defines a GetString() function which will accept user input as text from the terminal window.

In addition to the GetString() function, the cs50 library also defines a string data type (which is NOT a native C data type!).

We can add the cs50 library to our machine by following the instructions from the cs50 site. During the process, the library will be compiled, and the output placed in the /usr/local/lib/ directory, and the all-important header files will be added to our usr/local/include/ directory.

NOTE: You don't need to focus on using this course-specific library specifically here - this is simply an example of adding an external include to the compilation process.

Once added, the various functions and types defined therein will be available to us.

We might modify our simple Hello World! example as follows by referencing the cs50 library, and making use of the GetString() function and the new string type:

Modified Hello World Example:
// Add include for cs50 library:
#include <cs50.h>
#include <stdio.h>
  
int main(void)
{
    printf("What is your name?");
    // Get text input from user:
    string name = GetString();
      
    // Use user input in output striing:
    printf("Hello, %s\n", name);
}

 

Now, if we try to use the same terminal command to compile this version, we will see some issues:

Run Original Compile Command:
$ clang hello.c -o hello

 

Terminal Output from Command:
/tmp/hello-E2TvwD.o: In function `main':
hello.c:(.text+0x22): undefined reference to `GetString'
clang: error: linker command failed with exit code 1 
    (use -v to see invocation)

 

From the terminal output, we can see that the compiler cannot find the GetString() method, and that there was an issue with the linker.

Turns out, we can add some additional arguments to our clang command to tell Clang what files to link:

$ clang hello.c -o hello -lcs50

 

By adding the -l flag followed by the name of the library we need to include, we have told Clang to link to the cs50 library.

Handling Errors and Warnings

Of course, the examples of using the Clang compiler and arguments above still represent a very basic case. Generally, we might want to direct the compiler to add compiler warnings, and/or to include debugging information in the output files. a simple way to do this from the terminal, using our example above, would be as follows:

Adding Additional Compiler Flags to clang Terminal Command:
clang hello.c -g -Wall -o hello -lcs50

 

Here, we have user the -g flag, which tells the compiler to include debugging information in the output files, and the -Wall flag. -Wall turns on most of the various compiler warnings in Clang (warnings do not prevent compilation and output, but warn of potential issues).

A quick skimming of the Clang docs will show that there is potential for a great many compiler flags and other arguments.

As we can see, though, our terminal input to compile even the still-simple hello application is becoming cumbersome. Now imagine a much larger application, with multiple source files, referencing multiple external libraries.

What is Make?

Since source code can be contained in multiple files, and also make reference to additional files and libraries, we need a way to tell the compiler which files to compile, which order to compile them, and how a link to external files and libraries upon which our source code depends. With the additional of various compiler options and such required to get our application running, combined with the frequency with which we are likely to use the compile/run cycle during development, it is easy to see how entering the compile commands manually could rapidly become cumbersome.

Enter the Make utility.

GNU Make was originally created by Richard M. Stallman ("RMS") and Roland McGrath. From the GNU Manual:

"The make utility automatically determines which pieces of a large program need to be recompiled, and issues commands to recompile them."

When we write source code in C, C++, or other compiled languages, creating the source is only the first step. The human-readable source code must be compiled into binary files in order that the machine can run the application.

Essentially, the Make utility utilizes structured information contained in a makefile in order to properly compile and link a program. A Make file is named either Makefile or makefile, and is placed in the source directory for your project.

An Example Makefile for Hello World

Our final example using the clang command in the terminal contained a number of compiler flags, and referenced one external library. The command was still doable manually, but using make, we can make like much easier.

In a simple form, a make file can be set up to essentially execute the terminal command from above. The basic structure looks like this:

Basic Makefile Structure:
# Compile an executable named yourProgram from yourProgram.c
all: yourProgram.c
<TAB>gcc -g -Wall -o yourProgram yourProgram.c

 

In a makefile, lines preceded with a hash symbol are comments, and will be ignored by the utility. In the structure above, it is critical that the <TAB> on the third line is actually a tab character. Using Make, all actual commands must be preceded by a tab.

For example, we might create a Makefile for our hello program like this:

Makefile for the Hello Program:
# compile the hello program with compiler warnings, 
# debug info, and include the cs50 library
all: hello.c
	clang -g -Wall -o hello hello.c -lcs50

 

This Make file, named (suitably) makefile and saved in the directory where our hello.c source file lives, will perform precisely the same as the final terminal command we examined. In order to compile our hello.c program using the makefile above, we need only type the following into our terminal:

Compiling Hello Using Make:
$ make

 

Of course, we need to be in the directory in which the make file and the hello.c source file are located.

A More General Template for Make Files

Of course, compiling our Hello World application still represents a pretty simplistic view of the compilation process. We might want to avail ourselves of the Make utilities strengths, and cook up a more general template we can use to create make files.

The Make utility allows us to structure a makefile in such a way as to separate the compilation targets (the source to be compiled) from the commands, and the compiler flags/arguments (called rules in a make file). We can even use what amount to variables to hold these values. 

For example, we might refine our current makefile as follows:

General Purpose Makefile Template:
# the compiler to use
CC = clang
  
# compiler flags:
#  -g    adds debugging information to the executable file
#  -Wall turns on most, but not all, compiler warnings
CFLAGS  = -g -Wall
  
#files to link:
LFLAGS = -lcs50
  
# the name to use for both the target source file, and the output file:
TARGET = hello
  
all: $(TARGET)
  
$(TARGET): $(TARGET).c
	$(CC) $(CFLAGS) -o $(TARGET) $(TARGET).c $(LFLAGS)

 

As we can see in the above, we can make assignments to each of the capitalized variables, which are then used in forming the command (notice that once again, the actual command is preceded by a tab in the highlighted line). While this Make File is still set up for our Hello World application, we could easily change the assignment to the TARGET variable, as well as add or remove compiler flags and/or linked files for a different application.

Again, we can tell make to compile our hello application by simply typing:

Compile Hello.c Using the modified Makefile:
$ make

 

A Note on Tabs Vs. Spaces in Your Editor

If you, like me, follow the One True Coding Convention which states:

"Thou shalt use spaces, not tabs, for indentation"

Then you will have a problem with creating your make file. If you have your editor set to convert tabs to spaces, Make will not recognize the all-important Tab character in front of the command, because, well, it's not there.

Fortunately, there is a work-around. If you do not have tabs in your source file, you can instead separate the compile target from the command using a semi-colon. With this fix in place, our Make file might look like this:

Makefile with no Tab Characters:
# Compile an executable named yourProgram from yourProgram.c
all: yourProgram.c
<TAB>gcc -g -Wall -o yourProgram yourProgram.c
# compile the hello program with spaces instead of Tabs
  
# the compiler to use
CC = clang
  
# compiler flags:
#  -g    adds debugging information to the executable file
#  -Wall turns on most, but not all, compiler warnings
CFLAGS  = -g -Wall
  
#files to link:
LFLAGS = -lcs50
  
# require that an argument be provided at the command line for the target name:
TARGET = hello
  
all: $(TARGET)
$(TARGET): $(TARGET).c ; $(CC) $(CFLAGS) -o $(TARGET) $(TARGET).c $(LFLAGS)

 

In the above, we have inserted a semi-colon between the definition of dependencies definition of the target and the command statement structure (see highlighted line).

Passing the Compilation Target Name to Make as a Command Line Argument

Most of the time, when developing an application you will most likely need a application-specific Makefile for the application. At least, any substantive application which includes more than one source file, and/or external references.

However, for simple futzing about, or in my case, tossing together a variety of one-off example tidbits which comprise the bulk of the problem sets for the Harvard cs50 course, it may be handy to be able to pass the name of the compile target in as a command line argument. The bulk of the Harvard examples include the cs50 library created by the program staff (at least, in the earlier exercises), but otherwise would mostly require the same sets of arguments.

For example, say we had another code file, goodby.c in the same directory.

We could simply pass the target name like so:

Passing the Compilation Target Name as a Command Line Argument:
make TARGET=goodbye.c

 

As we can see, we assign the target name to the TARGET variable when we invoke Make. In this case, if we fail to pass a target name, by simply typing make as we have done previously, Make will compile the program hard-coded into the Makefile - in this case, hello. Despite our intention, the wrong file will be compiled.

We can make one more modification to our Makefile if we want to require that a target be specified as a command line argument:

Require a Command Line Argument for the Compile Target Name:
# compile the hello program with spaces instead of Tabs
  
# the compiler to use
CC = clang
  
# compiler flags:
#  -g    adds debugging information to the executable file
#  -Wall turns on most, but not all, compiler warnings
CFLAGS  = -g -Wall
  
#files to link:
LFLAGS = -lcs50
  
# require that an argument be provided at the command line for the target name:
TARGET = $(target)
  
all: $(TARGET)
$(TARGET): $(TARGET).c ; $(CC) $(CFLAGS) -o $(TARGET) $(TARGET).c $(LFLAGS)

 

With that change, we can now run make on a simple, single-file program like so:

Invoke Make with Required Target Name:
$ make target=hello

 

Of course, now things will go a little haywire if we forget to include the target name, or if we forget to explicitly make the assignment when invoking Make from the command line.

Only the Beginning

This is one of those posts that is mainly for my own reference. As I become more fluent with C, compilation, and Make, I expect my usage may change. For now, however, the above represents what I have figured out while trying to work with the examples in the on-line Harvard course.

If you see me doing anything idiotic in the above, or have suggestions, I am all ears! Please do comment below, or reach out at the email described in my "About the Author" blurb at the top of this page.

Additional Resources and Items of Interest

 

Posted on July 6 2014 02:30 PM by jatten     

Comments (3)

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