Search code examples
c#asp.net-mvc-5asp.net-identity-2user-roles

Adding Identity 2.0 Roles to custom Identity


I recently started work on a new application using MVC 5 and Identity 2.0, in order to use a different password hashing algorithm I implemented the custom identity detailed in this guide (https://code.msdn.microsoft.com/ASPNET-45-MVC5-Custom-1a94ab26#content).

I have looked at various ways of incorporating roles into this identity implementation but so far have not found a way of making them work with this new identity implementation.

Does anyone now of a guide on how to go about adding roles to a similar custom identity provider?

Any guidance would be very much appreciated.


Solution

  • Your implementation of IdentityUser (ApplicationUser: if you're using the standard template) will provide the methods to associate a user with roles: AddToRoleAsync, AddToRolesAsync, GetRolesAsync, RemoveFromRolesAsync.

    If you want to manage roles, as I suspect, you have to add a RoleManager<IdentityRole>.

    public class ApplicationRoleManager : RoleManager<IdentityRole>
        {
            public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
                : base(roleStore)
            {
            }
    
            public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
            {
                var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
    
                return appRoleManager;
            }
        }
    

    and add this to the owin context:

    app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
    

    The ApplicationRoleManager will allow you to create roles (CreateAsync), find (FindByIdAsync), delete (DeleteAsync).

    While your ApplicationUserManager:

    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
      ...
    }
    

    will allow you to associate role with a user (AddToRoleAsync), remove (RemoveFromRoleAsync).

    If you have implemented your UserStore using the interface IUserStore, then you need to implement IUserRoleStore as well.

    In this last interface you can find AddToRoleAsync, GetRolesAsync, IsInRoleAsync, RemoveFromRoleAsync.

    You have to implement your RoleStore (IRoleStore) as well.

    If you want to read some good articles about this topic I would suggest you to have a look at this blog. This guy has written 4 articles so far about ASP.NET Identity 2.x:

    Part 1
    Part 2
    Part 3
    Part 4 (the one you're interested in)

    And this is another guy who writes interesting stuff on the topic.