Creating Roles in Asp.net Identity MVC 5

前端 未结 11 1365
情深已故
情深已故 2020-12-02 05:09

There is very little documentation about using the new Asp.net Identity Security Framework.

I have pieced together what I could to try and create a new Role and add

相关标签:
11条回答
  • 2020-12-02 05:36

    In ASP.NET 5 rc1-final, I did following:

    Created ApplicationRoleManager (in similar manner as there is ApplicationUser created by template)

    public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(
            IRoleStore<IdentityRole> store,
            IEnumerable<IRoleValidator<IdentityRole>> roleValidators,
            ILookupNormalizer keyNormalizer,
            IdentityErrorDescriber errors,
            ILogger<RoleManager<IdentityRole>> logger,
            IHttpContextAccessor contextAccessor)
            : base(store, roleValidators, keyNormalizer, errors, logger, contextAccessor)
        {
        }
    }
    

    To ConfigureServices in Startup.cs, I added it as RoleManager

    services.
        .AddIdentity<ApplicationUser, IdentityRole>()
        .AddRoleManager<ApplicationRoleManager>();
    

    For creating new Roles, call from Configure following:

    public static class RoleHelper
    {
        private static async Task EnsureRoleCreated(RoleManager<IdentityRole> roleManager, string roleName)
        {
            if (!await roleManager.RoleExistsAsync(roleName))
            {
                await roleManager.CreateAsync(new IdentityRole(roleName));
            }
        }
        public static async Task EnsureRolesCreated(this RoleManager<IdentityRole> roleManager)
        {
            // add all roles, that should be in database, here
            await EnsureRoleCreated(roleManager, "Developer");
        }
    }
    
    public async void Configure(..., RoleManager<IdentityRole> roleManager, ...)
    {
         ...
         await roleManager.EnsureRolesCreated();
         ...
    }
    

    Now, the rules can be assigned to user

    await _userManager.AddToRoleAsync(await _userManager.FindByIdAsync(User.GetUserId()), "Developer");
    

    Or used in Authorize attribute

    [Authorize(Roles = "Developer")]
    public class DeveloperController : Controller
    {
    }
    
    0 讨论(0)
  • 2020-12-02 05:39

    Here we go:

    var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    
    
       if(!roleManager.RoleExists("ROLE NAME"))
       {
          var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
          role.Name = "ROLE NAME";
          roleManager.Create(role);
    
        }
    
    0 讨论(0)
  • 2020-12-02 05:40

    As an improvement on Peters code above you can use this:

       var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
    
       if (!roleManager.RoleExists("Member"))
                roleManager.Create(new IdentityRole("Member"));
    
    0 讨论(0)
  • 2020-12-02 05:41
        public static void createUserRole(string roleName)
        {
            if (!System.Web.Security.Roles.RoleExists(roleName))
            {
                System.Web.Security.Roles.CreateRole(roleName);
            }
        }
    
    0 讨论(0)
  • 2020-12-02 05:42

    Here is the complete article describing how to create role, modify roles, delete roles and manage roles using ASP.NET Identity. This also contains User interface, controller methods etc.

    http://www.dotnetfunda.com/articles/show/2898/working-with-roles-in-aspnet-identity-for-mvc

    Hope this helpls

    Thanks

    0 讨论(0)
  • 2020-12-02 05:43

    Roles View Model

    public class RoleViewModel
    {
        public string Id { get; set; }
        [Required(AllowEmptyStrings = false)]
        [Display(Name = "RoleName")]
        public string Name { get; set; }
    }
    

    Controller method

        [HttpPost]
        public async Task<ActionResult> Create(RoleViewModel roleViewModel)
        {
           if (ModelState.IsValid)
           {
               var role = new IdentityRole(roleViewModel.Name);
               var roleresult = await RoleManager.CreateAsync(role);
               if (!roleresult.Succeeded)
               {
                   ModelState.AddModelError("", roleresult.Errors.First());
                   return View();
               }
               return RedirectToAction("some_action");
           }
           return View();
        }
    
    0 讨论(0)
提交回复
热议问题