I used below snippets on a single asp.net page_load webpage to understand how 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 created using ASP.NET 4.5+ templates, as shown below
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection") { } }
Also create an application role manager class
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 the line below to your startup.Auth.cs => ConfigureAuth (IAppBuilder method)
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
I'm new to this Identity Stuff, and I'm not sure if this is necessary, or I make it clean and right, but these steps worked for me
Iman Abidi Nov 18 '16 at 14:32 2016-11-18 14:32
source share