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 documen
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(new ApplicationDbContext());
var roleManager = new RoleManager(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
{
public ApplicationDbContext()
: base("DefaultConnection")
{
}
}
Also Create application Role Manager class too
public class ApplicationRoleManager : RoleManager
{
public ApplicationRoleManager(IRoleStore roleStore)
: base(roleStore)
{
}
public static ApplicationRoleManager Create(IdentityFactoryOptions options, IOwinContext context)
{
//return new ApplicationRoleManager(new RoleStore(context.Get()));
return new ApplicationRoleManager(new RoleStore(new ApplicationDbContext()));
}
}
also add below line in your startup.Auth.cs => ConfigureAuth(IAppBuilder app) method
app.CreatePerOwinContext(ApplicationRoleManager.Create);
And then in your controller:
private ApplicationRoleManager _roleManager;
public ApplicationRoleManager RoleManager
{
get
{
return _roleManager ?? HttpContext.GetOwinContext().Get();
}
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