如果您想通过角色来授权,则需要使用创建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