![](/img/trans.png)
[英]ASP.NET MVC: How to properly reference custom object to ApplicationUser?
[英]Asp.Net MVC authorize a custom user which extends ApplicationUser
我正在使用內置的身份驗證/授權系統,其中ApplicationUser
需要登錄並進行身份驗證,然后使用SignInManager
。
我還有一個不同的用戶CustomUser
,它擴展了ApplicationUser
。 CustomUser
通過外部服務進行身份驗證。 一旦他通過身份驗證,我將檢查他是否存在,如果不存在,我將創建他並給他CustomRole
。
如何使CustomUser
獲得授權? 我希望能夠將[Authorize(Roles="CustomRole")]
屬性放在應該允許他執行的操作上方。 那可能嗎? 我需要做些什么才能使它工作? 或者,還有更好的方法?
編輯
這是CustomUser的實現。 它位於Application.Models下
public class CustomUser : ApplicationUser
{
public int Gender
{
get;
set;
}
public string FCode
{
get;
set;
}
public bool Subscribed
{
get;
set;
}
}
這是CustomUser
的簡化版本。
對於角色,您應該可以執行以下操作:
[Authorize(Roles = "CustomRole")]
public ActionResult CustomRoleOnly()
{
return View();
}
還是給用戶的
[Authorize(Users = "JoeBloggs, JaneDoe")]
public ActionResult SpecificUserOnly()
{
return View();
}
如果要按角色授權,則需要使用以下方法創建Roles
:
userManager.AddToRole(user.Id, "NameOfRole");
您可以像下面那樣創建一個注冊動作,任何注冊用戶都來自一個角色。 您可以為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..")]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.