0

我正在使用內置認證/授權系統,其中ApplicationUser需要登錄,一旦通過身份驗證,他就使用SignInManager登錄。Asp.Net MVC授權擴展ApplicationUser的自定義用戶

我也有不同的用戶,CustomUser,它延伸ApplicationUserCustomUser通過外部服務進行身份驗證。一旦他被認證,我檢查他是否存在,如果沒有,我創建他並給他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的簡化版本。

回答

0

如果您想通過角色來授權,則需要使用創建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..")] 
+0

問題是SignInManager只接受ApplicationUser,而不接受擴展的CustomUser。我設法創建了CustomUser並添加了正確的角色,但是現在我需要能夠「簽名」或以某種方式告訴系統哪個用戶正在使用該系統,如果這有意義的話?那麼是否有可能獲得SignInManager 的實例可以簽名? – joks

+0

@joks是你的CustomUser是由'IdentityUser'實現的嗎? – Valkyrie

+0

@joks看這篇文章隊友,你不需要爲自定義用戶創建一個模型,你可以使用ApplicationUser,如果你想給它額外的屬性,你可以將它添加到它的類,像這篇文章:http:// stackoverflow .com/questions/28335353/how-to-extend-available-properties-of-user-identity – Valkyrie

0

你應該能夠爲角色做類似如下:

[Authorize(Roles = "CustomRole")] 
public ActionResult CustomRoleOnly() 
{ 
    return View(); 
} 

,或者如果它是爲用戶

[Authorize(Users = "JoeBloggs, JaneDoe")] 
public ActionResult SpecificUserOnly() 
{ 
    return View(); 
}