如果您想通過角色來授權,則需要使用創建Roles
:
userManager.AddToRole(user.Id, "NameOfRole");
您可以創建一個類似下面的註冊操作,任何註冊表ered用戶將來自一個角色。您可以爲Manager
創建其他角色,並稍後更新特定用戶。
using (var context = new ApplicationDbContext())
{
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);
//adding a role after register
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
userManager.AddToRole(user.Id, "SimpleUser");
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
}
然後在您的授權屬性上,您可以使用Roles
來授權。
[Authorize(Roles="Manager, SimpleUser, so on..")]
問題是SignInManager只接受ApplicationUser,而不接受擴展的CustomUser。我設法創建了CustomUser並添加了正確的角色,但是現在我需要能夠「簽名」或以某種方式告訴系統哪個用戶正在使用該系統,如果這有意義的話?那麼是否有可能獲得SignInManager的實例可以簽名? –
joks
@joks是你的CustomUser是由'IdentityUser'實現的嗎? – Valkyrie
@joks看這篇文章隊友,你不需要爲自定義用戶創建一個模型,你可以使用ApplicationUser,如果你想給它額外的屬性,你可以將它添加到它的類,像這篇文章:http:// stackoverflow .com/questions/28335353/how-to-extend-available-properties-of-user-identity – Valkyrie