ASP.NET Identity 將使用者加入角色
一、於 IdentityConfig.cs 先建立角色管理員
//增加角色管理員相關的設定
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>()));
}
}
二、於App_Start \ Startup.Auth.cs加入
//增加腳色的OwinContext
app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
三、於AccountController.cs加入
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
//角色名稱
var roleName = "Test";
//判斷角色是否存在
if (HttpContext.GetOwinContext().Get<ApplicationRoleManager>().RoleExists(roleName) == false)
{
//角色不存在,建立角色
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole(roleName);
await HttpContext.GetOwinContext().Get<ApplicationRoleManager>().CreateAsync(role);
}
//將使用者加入該角色
await UserManager.AddToRoleAsync(user.Id, roleName);
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
完成後可以對想要限制角色的Action加上[Authorize(Role="Test")]過濾器即可,
代表此 Action 只能允許 Test 角色進入,
另外有一個完整的角色使用範例可參考,
於 NuGet 套件管理器主控台輸入Install-Package Microsoft.AspNet.Identity.Samples -Pre指令即可