简体   繁体   中英

Add role in ASP.NET Identity

How can I add a Role in the new ASP.NET Identity system (1.0)? There is a UserStore class but no RoleStore class.

I can't find any documentation on this issue.

RoleManager = new RoleManager<IdentityRole>(
                  new RoleStore<IdentityRole>(new MyDbContext()));
var roleresult = RoleManager.Create(new IdentityRole(roleName));

Starting with the .NET Framework 4.5, Windows Identity Foundation (WIF) has been fully integrated into the .NET Framework.

I would advice to examine the possibility, in my opinion the preferred, to implement Authorization through Claims ( Expressing Roles as Claims ).

When the IsInRole() method is called, there is a check made to see if the current user has that role. In claims-aware applications, the role is expressed by a role claim type that should be available in the token.

The role claim type is expressed using the following URI: " http://schemas.microsoft.com/ws/2008/06/identity/claims/role "

So from the UserManager you can do something like this (without the RoleManager):

var um = new UserManager();
um.AddClaimAsync(1, new Claim(ClaimTypes.Role, "administrator"));

Claims can simplify and increase the performance of authentication and authorization processes. You can use the roles stored as claims to eliminate back-end queries every time authorization takes place.

Using Claims you will not need the RoleStore anymore (at least for the equivalent authorization purposes...)

I used below snippets in one sample asp.net web page page_load for starting to grasp the way ASP Identity works

   UserManager userManager = new UserManager();
    var roleStore = new RoleStore<IdentityRole>(new ApplicationDbContext());
    var roleManager = new RoleManager<IdentityRole>(roleStore);
    var applicationRoleAdministrator = new IdentityRole("superadmin");
    if (!roleManager.RoleExists(applicationRoleAdministrator.Name))
    {
        roleManager.Create(applicationRoleAdministrator);
    }
     ApplicationUser applicationUserAdministrator = userManager.FindByName(User.Identity.Name);

    if (!userManager.GetRoles(applicationUserAdministrator.Id).Contains("superadmin"))
    {
        Response.Redirect("~/account/login.aspx?ReturnUrl=" + Request.Url.AbsolutePath);
    }

Of course below ApplicationDbContext is automatically generated with ASP.NET 4.5+ templates like below

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }
    }

Also Create application Role Manager class too

public class ApplicationRoleManager : RoleManager<IdentityRole>
{
    public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        //return new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));
        return new ApplicationRoleManager(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    }
}

also add below line in your startup.Auth.cs => ConfigureAuth(IAppBuilder app) method

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

And then in your controller:

private ApplicationRoleManager _roleManager;

public ApplicationRoleManager RoleManager
{
    get
    {
        return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
    }
    private set
    {
        _roleManager = value;
    }
}

I am new to this Identity Stuff and I am not sure if it is necessary or I am doing it clean and right, but these steps worked for me

ASP.NET identity is claims aware with respect to roles. That really confused me because in the previous system you configured membership and role providers in web.config.

The issue for me is that I have code like this:

HttpContext.Current.User.IsInRole("some role")

Fortunately, this logic still works. You can see the logic in the CreateAsync function in ClaimsIdentityFactory.cs which is in Microsoft.AspNet.Identity.Core . One of the arguments is UserManager . It asks it if it SupportsUserRole and if so then it calls GetRolesAsync and adds each role as a claim to the ClaimIdentity . There is no need to do this yourself.

IsInRole uses claims as described here:

http://msdn.microsoft.com/en-us/library/hh545448.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM