ASP.NET Identity 2.0 has been included in the standard template since Visual Studio 2013.
It’s available in MVC and WebAPI as ONE ASP.NET.
Where is Role?
Role based access control has managed user access since Form Authentication but it’s missing in the current template.
Just adding some code snippets to the template as follows in order to enable this.
Models/IdentityModels.cs
public class ApplicationRole : IdentityRole { }
App_Start/IdentityConfig.cs
public class ApplicationRoleManager : RoleManager<ApplicationRole, string> { public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store) : base(store) { } public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context) { var dbContext = context.Get<ApplicationDbContext>(); var roleStore = new RoleStore<ApplicationRole>(dbContext); var manager = new ApplicationRoleManager(roleStore); // Add some roles (e.g. "Administrator") if needed if (!manager.Roles.Any(r => r.Name == "Administrator")) { manager.Create(new ApplicationRole { Name = "Administrator" }); } return manager; } }
Models/IdentityModels.cs
public partial class Startup { public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager≥(ApplicationUserManager.Create); // Add this line app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); } }
Controllers/AccountController.cs
public class AccountController : Controller { private ApplicationUserManager _userManager; private ApplicationRoleManager _roleManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationRoleManager roleManager, ApplicationSignInManager signInManager) { UserManager = userManager; RoleManager = roleManager; SignInManager = signInManager; } public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } } }
If DB is existing, it’s need to be renewed.
Execute the following commands in Package Manager
PM> Enable-Migrations PM> Add-Migration "AddRole" PM> Update-Database