net mvc management implement how for asp c# asp.net-mvc-5 asp.net-identity

c# - implement - mvc 5 identity user management



Crear roles en Asp.net Identity MVC 5 (10)

Aquí está el artículo completo que describe cómo crear roles, modificar roles, eliminar roles y administrar roles usando ASP.NET Identity. Esto también contiene interfaz de usuario, métodos de controlador, etc.

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

Espero que esto ayude

Gracias

Hay muy poca documentación sobre el uso del nuevo Asp.net Identity Security Framework.

He reconstruido todo lo que pude para intentar crear un nuevo Rol y agregarle un Usuario. Intenté lo siguiente: Agregar rol en ASP.NET Identity

que parece que puede haber obtenido la información de este blog: crear una aplicación simple para hacer con identidad asp.net y asociar usuarios con "to-does"

He agregado el código a un inicializador de base de datos que se ejecuta cada vez que cambia el modelo. Falla en la función RoleExists con el siguiente error:

System.InvalidOperationException produjo en mscorlib.dll El tipo de entidad IdentityRole no forma parte del modelo para el contexto actual.

protected override void Seed (MyContext context) { var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); // Create Admin Role string roleName = "Admins"; IdentityResult roleResult; // Check to see if Role Exists, if not create it if (!RoleManager.RoleExists(roleName)) { roleResult = RoleManager.Create(new IdentityRole(roleName)); } }

Cualquier ayuda es apreciada.


Aquí vamos:

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); }


Como una mejora en el código de Peters anterior puedes usar esto:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); if (!roleManager.RoleExists("Member")) roleManager.Create(new IdentityRole("Member"));


En ASP.NET 5 rc1-final , hice lo siguiente:

Creado ApplicationRoleManager (de manera similar a como está ApplicationUser creado por plantilla)

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) { } }

Para ConfigureServices Startup.cs in Startup.cs , lo agregué como RoleManager

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

Para crear nuevas funciones, llame desde Configure siguiente:

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(); ... }

Ahora, las reglas se pueden asignar al usuario

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

O usado en el atributo Authorize

[Authorize(Roles = "Developer")] public class DeveloperController : Controller { }


Mi aplicación estaba pendiente de inicio cuando utilicé las muestras de código de Peter Stulinski y Dave Gordon con EF 6.0. Cambié:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));

a

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(**context**));

Lo cual tiene sentido cuando en el método de semilla no quiere crear una instancia de otra instancia de ApplicationDBContext . Esto podría haberse complicado por el hecho de que tenía Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer()); en el constructor de ApplicationDbContext


Modelo de vista de roles

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

Método del controlador

[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(); }


Quería compartir otra solución para agregar roles:

<h2>Create Role</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <span class="label label-primary">Role name:</span> <p> @Html.TextBox("RoleName", null, new { @class = "form-control input-lg" }) </p> <input type="submit" value="Save" class="btn btn-primary" /> }

Controlador:

[HttpGet] public ActionResult AdminView() { return View(); } [HttpPost] public ActionResult AdminView(FormCollection collection) { var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext())); if (roleManager.RoleExists(collection["RoleName"]) == false) { Guid guid = Guid.NewGuid(); roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = collection["RoleName"] }); } return View(); }


Verifique que tiene la siguiente firma de su clase MyContext

public class MyContext : IdentityDbContext<MyUser>

O

public class MyContext : IdentityDbContext

¡El código funciona para mí, sin ninguna modificación!


el método que utilizo para crear roles está a continuación, asignándolos a los usuarios en el código también aparece en la lista. el siguiente código está en "configuration.cs" en la carpeta de migraciones.

string [] roleNames = { "role1", "role2", "role3" }; var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); IdentityResult roleResult; foreach(var roleName in roleNames) { if(!RoleManager.RoleExists(roleName)) { roleResult = RoleManager.Create(new IdentityRole(roleName)); } } var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); UserManager.AddToRole("user", "role1"); UserManager.AddToRole("user", "role2"); context.SaveChanges();


public static void createUserRole(string roleName) { if (!System.Web.Security.Roles.RoleExists(roleName)) { System.Web.Security.Roles.CreateRole(roleName); } }