Adding Identity 2.0 Roles to custom Identity

馋奶兔 提交于 2019-12-11 11:19:02

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28961197/adding-identity-2-0-roles-to-custom-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!