Building a mongodb provider for the new ASP.NET Identity framework - Part 2 RoleStore And Sample

Several people have requested help understanding how to use the MongoDB provider in a real application. Turns out there's a sample available as a NuGet package Microsoft ASP.NET Identity Samples.

The sample works with EntityFramework. I took the sample, and commit by commit adapted it to use the MongoDB provider. Checkout the modified sample.

One thing the sample had, that the mongodb provider had not yet implemented was a RoleStore. I hesitated to add this to the mongodb provider simply because I don't run across too many use cases for dynamic roles in an application. When I do see this, it's often very custom to the application and providing a generic means to handle this isn't that valuable. With that said, I went ahead and added a simple implementation if someone wants to see how this works with the identity sample and how they may want to adapt it for their own application.

One of the design decisions in doing this was not to update user documents when roles are deleted and when role names were updated. Instead of trying to provide an implementation for unknown use cases, I decided to make the RoleStore operations virtual so they could be extended by consumers. I had a couple of thoughts I wanted to share:

  • I intended the original implementation of the roles array on user documents to store role names.
  • When a role is deleted, leaving the role on the user document shouldn't be a problem. Yes it's orphaned data, but this is the world of denormalized data and is typical when working with NoSQL databases. If that won't work in your use case, consider a multi update to remove the role from user documents.
  • When a role name is changed, you may or may not need to update user documents. If you just made a mistake in the process of setting up a new role, no big deal if it's not yet assigned to any users. This is the use case I targeted. If you're renaming a role after it's been in use, you'll need to modify the user documents accordingly. You could override the RoleStore's UpdateAsync to do this before the role is renamed, just be aware that there's no easy way to ensure consistency of this operation across documents.
  • If you want to avoid issues with renaming roles, you could store the id of a role, instead of the name, in the user document's roles array.


comments powered by Disqus