Kemal Emin Kemal Emin - 3 months ago 15
ASP.NET (C#) Question

Multiple independent registration and login forms .NET Identity 2.0

Creating a new project in MVC 5 initiates all necessary classes to handle roles and users, which I am fine in modifying for custom properties. What I could not figure out though is, in my scenario, I have multiple different types of users e.g. Master Admins, Admins, Authors, Vendors and Tenants.

All of these have different properties as well as some shared ones. Usually, I would implement each type's username & password in their respective database tables. The ASP.NET Identity is quite tempting in a way to have a centralised store of users with the advantage of managing authentication out of the box in a easy to use manner with action results.

I have read every single result from a google search but the only solution similar to my scenario was the use of claims (which as far as I understand is not specifically made to handle this specific situation)

I am wandering if there is a way asp.net identity supports this kind of scenario?

Any help would be appreciated. Thanks.

Answer

You have two choice to meet your purpose:

  1. Using a shared ApplicationUser class and do a separation of forms by the Roles authorization. So you can create a form with conditional inputs (limit what shows with if(User.IsInRole("UserTypeName")) in razor) based on User's roles using RoleManager or create separate views for each user type and authorize them on controller side.
  2. Using simple inheritance to implement each user type based on its properties.

like:

public class CustomUser: ApplicationUser
{
    ...
}

You'll end up with a Discriminator column in your AspNetUsers table that will help Entity Framework identity which class it should instantiate for the row (CustomUser or ApplicationUser). Then you can either just query as normal or if you only want one particular type or another, you can use OfType<T> like:

var customUsers = db.Users.OfType<CustomUser>();

Keep in mind that any property which you add to inherited class, must be nullable. You cannot require something like a DateTime on CustomUser to be required at the database-level, because it prevents to save an ApplicationUser, which does not that property. However, this is only an issue at the database-level. You can still use view models to make a particular property on CustomUser required from a front-end perspective.

Comments